繁体   English   中英

调用迭代函数的次数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM