[英]Number of time the iterative function is called
Would like to seek a bit of help from StackOverflow. 想从StackOverflow寻求帮助。 I am trying to print out the sequence of Fibonacci number and also the number of time the iterative function is called which is supposed to be
5
if the input is 5
. 我想打印出的Fibonacci数的顺序和也是时间迭代函数被调用这应该是数
5
,如果输入的是5
。
However, I am only getting 4199371
as a count which is a huge number and I am trying to solve the problem since four hours. 但是,我只得到
4199371
,这是一个巨大的数字,并且我试图解决四个小时以来的问题。 Hope anyone who could spot some mistake could give a hint. 希望任何发现错误的人都能提供提示。
#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;
}
First, initialize the variable 首先,初始化变量
c1 = 0;
so that you will not get any garbage value get printed. 这样就不会打印出任何垃圾值。
Secondly this: 其次:
if (fibIterative(x) != 0)
{
c1++;
}
will make 2*count - 1
your count. 将使
2*count - 1
您的计数。 You don't need that. 不用了
Edit : I have noticed that you have removed extra c1++;
编辑 :我注意到您已经删除了多余的
c1++;
from your first revision . 从您的第一个版本开始 。 Hence, the above problem is not more valid.
因此,上述问题不是更有效。 However, you are calling the function
fibIterative()
again to have a check, which is not a good idea. 但是,您再次调用函数
fibIterative()
进行检查,这不是一个好主意。 You could have simply print c1-1
at the end, to show the count. 您可能只需在末尾打印
c1-1
即可显示计数。
Thirdly, 第三,
for (int x = 0; x <= num; x++)
you are starting from 0
till equal to x
that means 0,1,2,3,4,5
total of 6 iterations; 您是从
0
开始直到等于x
,这意味着0,1,2,3,4,5
共6次迭代; not 5
. 不是
5
。
If you meant to start from x = 1
, you need this: 如果要从
x = 1
开始,则需要:
for (int x = 1; x <= num; x++)
{ ^
cout << fibIterative(x) << " ";
c1++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.