我需要从数据文件中读取数字并将结果输出到相应的字母等级,并将这些等级写入新文件。我设法让程序创建新文件,但它似乎没有写成绩。任何人都可以指出我哪里出错了?谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double n1=0.0, n2=0.0, n3=0.0;
double sum1=0.0, sum2=0.0, sum3=0.0;
double avg1,avg2,avg3;
int count=0.0;
char grade;
FILE *inFile;
FILE *outFile;
inFile = fopen("data.txt", "r");
if (inFile == NULL){
printf("\nFailed to open file.\n");
exit(1);
}
else
{
while(count<1001){
fscanf(inFile,"%lf %lf %lf",&n1,&n2,&n3);
sum1 += n1;
sum2 += n2;
sum3 += n3;
count ++;
}
avg1 = sum1/1000.00;avg2 = sum2/1000.00;avg3 = sum3/1000.00;
printf("\nSum of Column 1 is: %lf\n", sum1);
printf("\nAverage of Column 1 is: %lf\n",avg1);
printf("\nSum of Column 2 is: %lf\n", sum2);
printf("\nAverage of Column 2: %lf\n",avg2);
printf("\nSum of Column 3: %lf\n", sum3);
printf("\nAverage of Column 3 is: %lf\n",avg3);
outFile = fopen("grades.txt", "w");
while(fscanf(inFile,"%lf %lf %lf",&n1,&n2,&n3)!=EOF){
fscanf(inFile,"%lf %lf %lf",&n1,&n2,&n3);
outFile = fopen("grades.txt", "w");
fprintf(outFile,"%char\n",&grade);
if(n1||n2||n3 < 60)
grade = 'F';
if(n1||n2||n3 >= 60)
grade = 'D';
if(n1||n2||n3 >=70)
grade = 'C';
if(n1||n2||n3 >=80)
grade = 'B';
if(n1||n2||n3 >= 90)
grade = 'A';
}
}
fclose(inFile);
return 0;
}
答案 0 :(得分:1)
这一行
fprintf(outFile,"%char\n",&grade);
有很多问题
Fchar
"F"
grade
的地址而不是它的值,而"%c"
说明符需要char
而不是char *
,这将导致未定义行为。grade
未初始化。启用编译器警告,您将需要修复很多,并且
不要忽略fscanf()
返回的值,阅读手册或一些参考文档,以了解返回值的含义。
答案 1 :(得分:1)
对文件的写入由计算机的操作系统处理。
在循环之前打开输出文件一次,在循环内打开很多次。在循环之前只打开一次。否则,当您尝试打开已写入的文件进行写入时,系统可能会阻止。
您不关闭输出文件。在许多操作系统中,这会导致您的写作丢失。循环后添加fclose(outFile)
。
当然还要检查iharobs的回答。
答案 2 :(得分:0)
if(n1||n2||n3 < 60)
。这在C中是非法的,您需要单独比较每个值。有点像
if(n1<60 || n2<60 || n3<60)