我无法获取我的程序,这意味着将Fibonacci序列生成到文件中,然后将其读回。我不确定r =问题是在于扫描还是打印,但是我的数字确实很长,数字错误
#include<stdio.h>
int main(){
//Step 1
int N;
scanf(" %d", &N);
if(N > 2){
printf("You entered argument: %d\n", N);}
else{
printf("That is an illegal argument. N must be greater than 2.");
return 0;}
unsigned long a = 1;
unsigned long b = 1;
unsigned long c;
int count = 2;
FILE *fib;
fib = fopen("Fibonacci", "w+");
if (fib == NULL) {
printf("Open TestFile failed\n");
return -1;}
fprintf(fib, "%lu %lu ",a,b);
printf("%lu %lu ",a,b);
for(count; count < N; count++){
if(count % 4 == 0){
fprintf(fib, "\n");
printf("\n");}
c = a+b;
if(c < a){
printf("integer overflow, ending number generation.");
break;}
fprintf(fib, "%lu ",c);
printf("%lu ",c);
a = b;
b = c;
}
fflush(fib);
printf("\ncount = %d",count);
//Step 2
unsigned long med;
int middle;
unsigned long nums[count];
int j;
if(count % 2 == 1){
middle = (count/2);
for(j = 0; j < count; j++){
fscanf(fib, "%lu", &nums[j]);}
med = nums[middle];
printf("\nmedian = %lu", med);}
unsigned long test1 = nums[0];
unsigned long test2 = nums [1];
unsigned long test3 = nums [2];
printf("\nnums array: %lu %lu %lu",test1, test2, test3);
return 0;
}
如果输入为3,则输出为
You entered argument: 3
1 1 2
count = 3
median = 221891732872
nums array: 140733854067968 221891732872 26447888
答案 0 :(得分:1)
如Johnny Mopp所述,您不会回放文件,因此在第二步中,当您阅读时,您已经处于文件末尾。如果您已经测试了不同scanf的返回代码,那就很明显了。
您应关闭并重新打开文件,或致电
fseek(fib, 0L, SEEK_SET);
在第2步开始
无论如何:总是测试输入函数的结果。
答案 1 :(得分:0)
你可以:
rewind(fib);
将文件指针重置为文件的开头fclose(fib);
,然后使用fopen("Fibonacci", "r");
重新打开它,在这种情况下,第一个fopen
调用只能将"w"
作为第二个参数。我不是r+/w+
模式的忠实粉丝,它们在实践中没有太多用途(imo),除非你正在处理/dev/mem
等特殊文件。< / p>