【问题标题】:Fibonacci Sequence C program error斐波那契数列 C 程序错误
【发布时间】:2018-06-21 06:48:25
【问题描述】:

我正在尝试编写一个程序,它将斐波那契数列的前 2 个数字以及 n 的值作为输入。然后程序给出斐波那契数列第n位的输出。

#include <stdio.h>
#include <stdlib.h>

int main () {
    int n, i;
    int s[n - 1];
    int a, b;   

    printf("Enter two first two numbers:");
    scanf("%d %d", &a, &b);
    printf("Enter the value of n(3-100):");
    scanf("%d", &n);

    for (i = 2; i <= n - 1; i++) {
        s[i] = s[i - 1] + s[i - 2];
    }

    printf("The nth digit is %d", s[n - 1]);

    return(0);
}

我得到的是答案编号,后面跟着一些额外的任意数字

【问题讨论】:

  • 您在知道n 的值之前尝试分配s。 (但请注意,该数组是完全没有必要的。)
  • 您还有一个off by 1 错误。 int s[n-1]; 数组包含以 0 开头的 n-1 元素,因此最后一个有效索引是 n-2

标签: c fibonacci


【解决方案1】:

实际上要实现您的代码,不需要数组s[]

这可以简单地实现为:-

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n, i;
    int a, b;

    printf("Enter two first two numbers:");
    scanf("%d%d", &a, &b);                      // not scanf("%d %d", &a, &b);
    printf("Enter the value of n(3-100):");
    scanf("%d", &n);

    for (i = 1; i < n; i++)
    {
        b += a;
        a = b - a;
    }

    printf("The nth digit is %d\n", a);

    return (0);
}

输出:

Enter two first two numbers:0 1
Enter the value of n(3-100):5
The nth digit is 3                     // 0 1 1 2 3

【讨论】:

    【解决方案2】:

    在这里你定义了一个未知大小的数组,幸运的是n 不是 0 或 1 或负数。

    int s[n-1];
    

    这里你忽略了scanf的返回值,你真的应该检查它来验证扫描是否成功。

    scanf("%d %d",&a,&b);
    scanf("%d",&n);
    

    即使假设定义了一个有意义的数组,您也可以在此处设置一个循环以生成数组之外的索引:

    for (i=2 ; i<=n-1 ; i++)
    

    然后你在数组之外写(在循环的最后一次迭代期间):

    s[i]=
    

    有了这段代码,所有的赌注都没有了,你已经保证了未定义的行为,因此任何关于到底哪里出错的解释都是徒劳的。

    【讨论】:

      【解决方案3】:

      一些事情。如前所述,您正在尝试在n 被赋予值之前使用它。另外,在使用变量来确定数组大小时,您应该使用malloc()

      接下来,如果要计算第 n 个总和,则需要数组包含 n 元素,而不是 n-1

      第三,您读取了两个起始值,ab,但您从未使用它们来初始化数组的前两个元素。

      最后,您需要修复循环索引。 (实际上,一旦您将数组更改为具有n 元素而不是n-1 元素,您的索引就可以了,但是,当然首选使用i &lt; n 而不是i &lt;= n-1

      int main() {
          int n, i;
          int a, b;
      
          printf("Enter two first two numbers:");
          scanf("%d %d", &a, &b);
          printf("Enter the value of n(3-100):");
          scanf("%d", &n);
      
          int *s = malloc(n * sizeof(*s));
      
          s[0] = a;
          s[1] = b;
      
          for (i = 2; i < n; i++) {
              s[i] = s[i - 1] + s[i - 2];
          }
      
          printf("The nth digit is %d", s[n - 1]);
      
          return(0);
      }
      

      【讨论】:

      • 你不需要为此使用 malloc,除非它是一个非常大的数组 - C 已经有 VLA 近 20 年了(自 C99 以来)。
      • 好吧,Visual Studio 已经支持 C99 有一段时间了(自 VS 2015 以来?晚了 16 年?),而且您已经在上面的代码中使用了另一个 C99 功能(块中间的变量声明)。但我当然在挑剔-否则答案很好-投赞成票。 ;-)
      • 有趣,它仍然告诉我我需要一个常量值,我得稍微摸索一下。谢谢。
      • 是的,MS 花了很长时间才添加 C99 支持(我什至现在都不确定它是否 100% 兼容 C99)——当你尝试编写和维护交叉时非常痛苦平台代码,因为 C99 已经普及了很长时间了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 2010-12-20
      • 2013-03-04
      • 1970-01-01
      相关资源
      最近更新 更多