gpt4 book ai didi

c - 斐波那契数列C程序错误

转载 作者:行者123 更新时间:2023-11-30 18:34:41 26 4
gpt4 key购买 nike

我正在尝试编写一个程序,该程序将斐波那契数列的前 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);
}

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

最佳答案

实际上,要实现您的代码,不需要数组 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

关于c - 斐波那契数列C程序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50962064/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com