我试图打印出Fibonacci序列,但输出与预期输出不匹配。我使用了printf函数并引用了存储数据的数组,因此我不确定我的错误在哪里。我也得到了奇怪的输出。
如果m = 0,应该打印序列的循环被设计为打印第i个斐波纳契数,应该打印出每个斐波纳契数的8位数。 对于任何其他m,它为每个m在数组中存储n个更多空格,并且打印功能被设计为相应地打印。
当m = 0时,只打印前9个Fibbonacci数字,当m = 1时,只有前7个数字显示正确的位数。
我不确定我的错误在哪里。
代码:
#include <stdio.h>
#include <stdlib.h>
int main() {
int a, b, n;
//create a list for the Fibonacci sequence
printf("Enter n.\n");
scanf("%d", &n);
//store a long for each 8 places
int m;
printf("Enter level of precision.");
scanf("%d",&m);
long fibonacci[(m+1)*n];
fibonacci[0] = 0;
fibonacci[1] = 1;
for (int u = 2; u<((m+1)*n-1);u++) {
fibonacci[u] = 0;
}
printf("F_0 =%d\n",fibonacci[0]);
printf("F_1 =%d\n",fibonacci[1]);
int j,l;
for (int i = 2; i<n; i++) {
a = i-1;
b = i-2;
fibonacci[i] = fibonacci[a] + fibonacci[b];
fibonacci[n+i] = (fibonacci[i]-(fibonacci[i]%100000000))/100000000;
fibonacci[i] = fibonacci[i]%100000000;
for (j = 0;j<m;j++) {
fibonacci[(j+1)*n+i] = fibonacci[(j+1)*n+i] + fibonacci[(j+1)*n+a] + fibonacci[(j+1)*n+b];
fibonacci[(j+2)*n+i] = (fibonacci[(j+1)*n+i] - (fibonacci[(j+1)*n+i]%100000000)) / 100000000;
fibonacci[(j+1)*n+i] = fibonacci[(j+1)*n+i]%100000000;
}
printf("F_%d=",i);
for (l = 0;l<(m+1);l++) {
printf("%08d",fibonacci[(m-l)*n+i]);
}
printf("\n");
}
}
输出:
对于m = 0
Enter n.
20
Enter level of precision.0
F_0 =0
F_1 =1
F_2=00000001
F_3=00000002
F_4=00000003
F_5=00000005
F_6=00000008
F_7=00000013
F_8=00000021
F_9=00000034
表示m = 1:
Enter n.
20
Enter level of precision.1
F_0 =0
F_1 =1
F_2=0000000000000001
F_3=0000000000000002
F_4=0000000000000003
F_5=0000000000000005
F_6=0000000000000008
F_7=0000000000000013
F_8=00000021
F_9=00000034
F_10=00000055
F_11=00000089
F_12=00000144
F_13=00000233
F_14=00000377
F_15=00000610
F_16=00000987
F_17=00001597
F_18=00002584
F_19=00004181