用户输入前 2 个数字的斐波那契数列

Fibonacci Sequence with user inputting first 2 numbers

我正在编写一个 C 程序来获取斐波那契数,用户需要输入前 2 个数字,序列从那里开始。这是我的代码:

#include <stdio.h>
#define MAX_SIZE 100

int main()
{
    int i, input[MAX_SIZE];

    printf("please Enter first 2 digit of the Sequence\n");

    scanf("%d, %d" , &input[0], &input[1]);

    for (i = 2; i < MAX_SIZE; i++)
    {
        input[i] = input[i-2] + input[i-1];

     printf("%d\n", input[i]);
    }

    return 0;    
}

但是当我 运行 输入 2 和 3 的代码时,我得到这样的输出 1499141456,这显然不是序列。请帮忙

退出循环时i等于MAX_SIZE

printf("%d\n", input[i]);

您正在打印数组边界之外的值 (input[MAX_SIZE])。

将 print 语句放在 for 循环大括号内。

or (i = 2; i < MAX_SIZE; i++)
    {
    input[i] = input[i-2] + input[i-1];
    printf("%d\n", input[i]);
    }

因为你的代码中的结果比 int 可以处理的最大值大

Live example here!

来自Wikipedia

The number 2,147,483,647 (or hexadecimal 7FFF,FFFF16) is the maximum positive value for a 32-bit signed binary integer in computing. It is therefore the maximum value for variables declared as integers (e.g., as int) in many programming languages, and the maximum possible score, money, etc. for many video games.

这是错误的地方

[...]
433494437 + 701408733 = 1134903170
701408733 + 1134903170 = 1836311903
1134903170 + 1836311903 = -1323752223