[英]Number of time the iterative function is called
想從StackOverflow尋求幫助。 我想打印出的Fibonacci數的順序和也是時間迭代函數被調用這應該是數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
您的計數。 不用了
編輯 :我注意到您已經刪除了多余的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++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.