简体   繁体   English

C-错误的斐波那契数

[英]C - Wrong fibonacci numbers

I have written this C code to output Fibonacci numbers but I'm lost as to why it gives the wrong value, and also why the numbers occasionally go down . 我已经编写了此C代码来输出斐波那契数字,但是我不知道为什么它给出错误的值,以及为什么数字偶尔会下降 What's going wrong and how can I fix it? 怎么了,我该如何解决?

It gives me this sequence: 0, 0, 1, 1, 2, 1, 3, 4, 3, 5, 5, 6, 8, 7, 13, 8, 21, 9, 34. 它给出了以下顺序:0、0、1、1、2、1、3、4、3、5、5、6、8、7、13、8、21、9、34。

#include <stdio.h>
#include <math.h>
int MyFibonacciFunction(int n)
{
    if (n == 0) {
        return 0;
    } else {
        if (n == 1) {
            return 1;
        } else {
            return (MyFibonacciFunction((n - 1)) + MyFibonacciFunction((n - 2)));
        }
    }
}

void main()
{

        int a = 0;
        while (a < 10) {
            {
                printf("%d\n", a);
                printf("%d\n", MyFibonacciFunction(a));
                a = (a + 1);
            }
    }
}

I've changed your code as follows,try this it solves your problem: 我已按如下方式更改了您的代码,请尝试使用它来解决您的问题:

#include <stdio.h>

int MyFibonacciFunction(int n) {

      if(n == 0)
        return 0;
      else if(n == 1)
        return 1;
      else
        return (MyFibonacciFunction((n - 1)) + MyFibonacciFunction((n - 2)));

}

int main(void)
{

    int a = 0;
    while (a < 10)
        printf("%d\n", MyFibonacciFunction(a++));

    return 0;
}

If you don't have to use recursion, then don't use it. 如果您不必使用递归,则不要使用它。 If this is some recursion excercise, then it's ok. 如果这是一些递归练习,那就没关系。 Iterative programming is faster and saves memory(a lot). 迭代编程更快,并节省了很多内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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