我正在尝试编写一个程序,该程序将斐波那契数列的前 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 %dn", 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
在这里你定义了一个未知大小的数组,幸运的是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]=
使用此代码,所有赌注都关闭了,您已经保证了未定义的行为,因此任何关于到底出了什么问题的解释都是徒劳的。
有几件事。 如前所述,您正在尝试在n
被赋予值之前使用它。 此外,在使用变量确定数组大小时,应使用malloc()
。
接下来,如果您正在计算第 n 个总和,那么您需要数组具有n
个元素,而不是n-1
第三,你读入两个起始值,a
和b
,但你从不使用它们来初始化数组的前两个元素。
最后,您需要修复循环索引。 (实际上,一旦您将数组更改为具有n
元素而不是n-1
元素,您的索引就可以了,但是,当然最好使用i < n
而不是i <= 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);
}