【问题标题】:C fibonacci with a user input带有用户输入的 C 斐波那契
【发布时间】:2016-07-14 13:48:31
【问题描述】:

我正在尝试计算用户输入的斐波那契数列。因此,如果用户输入 10,程序将输出序列中最多 10 的所有数字,在这种情况下为 0、1、1、2、3、5、8

这是我的代码:

#include <stdio.h>
int main ()
{
    /* variable definition: */
    int a, b, usrNumber;
    /* Initialize */
    a = 0;
    b = 1;
    usrNumber = 0;
    /* Ask user for number */
    printf("Please enter a positive number\n");
    scanf("%d", &usrNumber);
    /* Conduct Loop */
    while (b < usrNumber)
    {
        printf("%d \n",a);
        a += b;
        printf("%d \n",b);
        b += a;
    }
    return(0);
}

当我运行它 10 和 60 时,序列会比预期的少一个数字。当我运行 90 或 300 时,序列按预期工作。关于为什么我不能让较低的数字工作的任何想法?

【问题讨论】:

    标签: c loops fibonacci


    【解决方案1】:

    您可以使用辅助变量,而不是每个循环执行两个步骤

    while (b < usrNumber) { 
      aux=b;
      b+=a;
      a=aux;
      printf("%d ",b);} 
    

    【讨论】:

      【解决方案2】:

      将循环更改为如下所示:

      while (a < usrNumber)
      {
          printf("%d ", a);
          if (b < usrNumber) { 
              printf("%d ", b);
          }
          a = a + b;
          b = b + a;
      }
      

      如果用户输入 10,那么到第三次循环运行结束时,a 为 8,b 为 13。因此,因为 b 大于 10,循环停止,a即使小于 10 也不会打印

      【讨论】:

      • 对不起,我的第一个版本错了,我刚刚更新了。
      • 这就是我要找的。我仍然不知道为什么当我放入 10 或 60 时我的原始代码不起作用,但它适用于 90 或 300...
      • 太棒了!我不知道,但可能是因为输入较小的数字时数字之间的距离较小
      • 如果这是您正在寻找的,请务必将其标记为已接受的答案!谢谢:)
      【解决方案3】:

      我有一段时间没有使用 C,所以下面的代码可能需要稍作改动,但在我看来,使用递归函数对斐波那契数列更有意义:

          int GetFibonacciSequence(int index, bool printOutput)
          {
              int ret = 0;
              //Root of the function
              if (index == 0 || index == 1)
              {
                  ret = index;
              }
              //Recursive portion
              else
              {
                  int a = GetFibonacciSequence(index - 2, false);
                  int b = GetFibonacciSequence(index - 1, printOutput);
                  ret = (a + b);
              }
              //Output
              if (printOutput)
              {
                  printf("%d ", ret);
              }
              return ret;
          }
      

      【讨论】:

        【解决方案4】:

        这是一种快速简便的方法。

        int main(){
            int a=0, c=1, b=1, sum=0, lim;
            scan("%d", &lim);
            while (C < lim){ printf("%d. ",c); c=a+b; a=b; b=c; }
            return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 2013-03-04
          • 1970-01-01
          • 1970-01-01
          • 2016-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多