1
這裏是我的代碼到目前爲止它編譯和運行,但在輸出文件中給出一個大整數,當只詢問斐波納契數爲0.從一個文件中讀取數字,找到每個數字的斐波那契數字並將斐波那契數字寫入一個新文件
我相信找到斐波納契數的循環是正確的,因爲我從另一個程序中複製了循環,我的功能正常。
#include <stdio.h>
#include <ctype.h>
#define SIZE 40
int main(void)
{
char ch, filename[SIZE]; //variables
int num;
int t1 = 0;
int t2 = 1;
int index;
int result;
FILE *fp;
printf("Please enter the filename to read: "); //asking for file that is to be read
gets(filename);
// "r" reads the file fopen opens the file
if ((fp = fopen(filename, "r")) == NULL)
{
printf("Cannot open the file, %s\n", filename);
}
else
{
puts("Successfully opened, now reading.\n"); //reads through file counting words, upper/lowercase letters, and digits.
while ((num=getw(fp)) != EOF)
{
if(num == 1) //if the nth term is 1
result = 0;
else if(num == 2) //if the nth term is 2
result = 1;
else //for loop to start at the 3rd term
{
for(index = 2; index <= num ; index++)
{
result = t1 + t2;
t1 = t2;
t2 = result;
}
}
}
}
fclose(fp); //closing the file
char filename2 [SIZE];
FILE *fp2;
fprintf(stdout, "Please enter the file name to write in: "); //asks for file that you want to write to
gets(filename2);
if ((fp2 = fopen(filename2, "w")) == NULL) //"w" for writing
{
printf("Cannot create the file, %s\n", filename2);
}
else
{
fprintf(fp2, "%d", result);
}
fclose(fp2); // closing the file
fprintf(stdout, "You are writing to the file, %s is done.\n", filename2);
return 0;
}
與getw一起使用的文本模式文件,這是可疑的。你能提供你的輸入文件的樣本嗎?它是文本/二進制? –
它是一個名爲input.in的文本文件 –