既然你说你是 C 初学者,这里有一些提示:):
#include <stdio.h>
int main () {
/*When you program in C, try to declare all your variables at the begining of the code*/
int max;
long long int fiNum[]={1,1}; /* malloc! It is allways the solution and the problem too, but stick with malloc
something like fiNum = malloc (n*sizeof(long int)); I never malloc a long int
so just verify if its like this...
*/
long long int x;
int i=1; /*Try to only initializes loop variables inside the loop, like: for(i=1; i< max; i++){}*/
printf("How many numbers do you want to get? ");
scanf("%d",&max);
printf("max: %d\n", max);
while (i<max) { /*Here you could use a for loop*/
printf("i value: %d\n",i);
x=fiNum[i]+fiNum[i-1];
printf("%lld ",x);
i++;
fiNum[i]=x;
}
printf("\nDone!\n");
return 0;
}
Obs.:我在我的 linux 中运行了你的代码,因为对向量位置的访问无效,它没有打印出我要求的所有数字。
现在,固定代码:
#include <stdio.h>
#include <stdlib.h>
int main () {
int max;
int i;
long long int *fiNum;
printf("How many numbers do you want to get? ");
scanf("%d",&max);
fiNum = malloc(max*sizeof(long int));
fiNum[0] = 1;
fiNum[1] = 1;
for (i = 1; i < max-1; i++)
fiNum[i+1] = fiNum[i]+fiNum[i-1];
for (i = 0; i < max; i++)
printf("fi[%d]: %d\n", i+1, fiNum[i]);
printf ("\nDone!\n");
return 0;
}