调用迭代函数的次数
Number of time the iterative function is called
想从 Whosebug 寻求一些帮助。我正在尝试打印斐波那契数列以及迭代函数被调用的次数,如果输入为 5
,则迭代函数应为 5
。
但是,我只得到 4199371
的计数,这是一个很大的数字,而且我已经尝试解决四个小时以来的问题。希望有错误的朋友指点一下
#include <iostream>
using namespace std;
int fibIterative(int);
int main()
{
int num, c1;
cout << "Please enter the number of term of fibonacci number to be displayed: ";
cin >> num;
for (int x = 0; x <= num; x++)
{
cout << fibIterative(x);
if (fibIterative(x) != 0) {
c1++;
}
}
cout << endl << "Number of time the iterative function is called: " << c1 << endl;
}
int fibIterative(int n)
{
int i = 1;
int j = 0;
for(int k = 1; k <= n; k++) {
j = i + j;
i = j - i;
}
return j;
}
首先,初始化变量
c1 = 0;
这样你就不会打印出任何垃圾值。
其次是:
if (fibIterative(x) != 0)
{
c1++;
}
将使 2*count - 1
成为您的计数。你不需要那个。
编辑:我注意到您从 first revision 中删除了多余的 c1++;
。因此,上述问题不是更有效。但是,您再次调用函数 fibIterative()
进行检查,这不是一个好主意。您可以在最后简单地打印 c1-1
,以显示计数。
第三,
for (int x = 0; x <= num; x++)
您从 0
开始直到等于 x
,这意味着 0,1,2,3,4,5
总共 6 次迭代;不是 5
.
如果您打算从 x = 1
开始,您需要:
for (int x = 1; x <= num; x++)
{ ^
cout << fibIterative(x) << " ";
c1++;
}
想从 Whosebug 寻求一些帮助。我正在尝试打印斐波那契数列以及迭代函数被调用的次数,如果输入为 5
,则迭代函数应为 5
。
但是,我只得到 4199371
的计数,这是一个很大的数字,而且我已经尝试解决四个小时以来的问题。希望有错误的朋友指点一下
#include <iostream>
using namespace std;
int fibIterative(int);
int main()
{
int num, c1;
cout << "Please enter the number of term of fibonacci number to be displayed: ";
cin >> num;
for (int x = 0; x <= num; x++)
{
cout << fibIterative(x);
if (fibIterative(x) != 0) {
c1++;
}
}
cout << endl << "Number of time the iterative function is called: " << c1 << endl;
}
int fibIterative(int n)
{
int i = 1;
int j = 0;
for(int k = 1; k <= n; k++) {
j = i + j;
i = j - i;
}
return j;
}
首先,初始化变量
c1 = 0;
这样你就不会打印出任何垃圾值。
其次是:
if (fibIterative(x) != 0)
{
c1++;
}
将使 2*count - 1
成为您的计数。你不需要那个。
编辑:我注意到您从 first revision 中删除了多余的 c1++;
。因此,上述问题不是更有效。但是,您再次调用函数 fibIterative()
进行检查,这不是一个好主意。您可以在最后简单地打印 c1-1
,以显示计数。
第三,
for (int x = 0; x <= num; x++)
您从 0
开始直到等于 x
,这意味着 0,1,2,3,4,5
总共 6 次迭代;不是 5
.
如果您打算从 x = 1
开始,您需要:
for (int x = 1; x <= num; x++)
{ ^
cout << fibIterative(x) << " ";
c1++;
}