#include <stdio.h>int main() { FILE *fp_score = fopen("score.txt", "r"); FILE *fp_result = fopen("result.txt", "w"); int score, sum = 0, count = 0, max = 0, min = 100; while (fscanf(fp_score, "%d", &score) != EOF) { sum += score; count++; if (score > max) { max = score; } if (score < min) { min = score; } } double average = (double)sum / count; fprintf(fp_result, "%.2lf %d %d", average, max, min); fclose(fp_score); fclose(fp_result); return 0;}这段代码无法实现功能,请修改这段代码
时间: 2024-03-17 09:46:06 浏览: 346
首先,需要检查文件是否成功打开。其次,在写入结果文件时,需要加上换行符,以免多次运行时结果叠加在一行中。最后,为了保证程序的可移植性,应该使用标准的文件路径分隔符(如"/"或"\")。
修改后的代码如下:
```
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp_score = fopen("score.txt", "r");
FILE *fp_result = fopen("result.txt", "w");
if (fp_score == NULL || fp_result == NULL) {
printf("Failed to open file!\n");
exit(1);
}
int score, sum = 0, count = 0, max = 0, min = 100;
while (fscanf(fp_score, "%d", &score) != EOF) {
sum += score;
count++;
if (score > max) {
max = score;
}
if (score < min) {
min = score;
}
}
double average = (double)sum / count;
fprintf(fp_result, "%.2lf\n%d\n%d\n", average, max, min);
fclose(fp_score);
fclose(fp_result);
return 0;
}
```
阅读全文