【发布时间】:2018-07-29 18:27:48
【问题描述】:
想从 StackOverflow 寻求一些帮助。我试图打印出斐波那契数的序列以及迭代函数被调用的次数,如果输入是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。 -
我鼓励您使用调试器。这是一个重要的问题解决工具,我想你会很快发现错误的。