#include <stdio.h>
int main(void)
{
int num, i, total, average, min, max;
min = num;
max = num;
FILE *ifile;
ifile = fopen("scores.txt", "r");
i = total = 0;
while (fscanf(ifile, "%d", &num) != EOF) {
i++;
total += num;
}
printf("The total of the integers is %d.\n", total);
printf("The number of integers in the file is %d.\n", i);
average = total/i;
printf("The average of the integers is %d.\n", average);
while (fscanf(ifile, "%d", &num) != EOF) {
if (num < min) {
printf ("The minimum is %d\n", min);
} else if (num > max) {
printf ("The maximum is %d\n", max);
}
}
fclose(ifile);
return (0);
}
错误的代码部分是关于mins / maxes的最终结果。 我不确定是否要为此设置循环,或者甚至自己制作最小和最大变量。
答案 0 :(得分:1)
你的min / max-detection循环中至少有三个问题:
首先,如chux所示,min
和max
未初始化;因此,当迭代数字时,语句if (num < min)...
远远不能保证正常工作(当然,max
也是如此)。
因此,使用min
初始化INT_MAX
,并使用max
初始化INT_MIN
(均在<limits.h>
中定义),以便已在第一次迭代中min
并且max
将设置为您文件中的值。
其次,检查if (num < min)...
会给你一个“本地”最小值,即到目前为止读取的所有数字的最小值,但不是“绝对”最小值,因为稍后可能会出现较小的数字。因此,min / max在循环结束时有效,而不是在迭代期间有效。
第三,if (num < min) ... else if (num > max)
至少在文件只包含一个数字时是错误的。
您的代码可能如下所示:
int min = INT_MAX;
int max = INT_MIN;
while (fscanf(ifile, "%d", &num) != EOF) {
if (num < min)
min = num;
if (num > max)
max = num;
}
// min/max are valid earliest at this point:
printf ("The minimum is %d\n", min);
printf ("The maximum is %d\n", max);
// Note that min/max will not be correct if the file does not contain any number;
// Note further, that fscanf(ifile, "%d", &num) != EOF may result in an endless loop if the file contains characters that "%d" will not read as a valid integral value.
// But this is left to the OP for further improvement :-)
答案 1 :(得分:0)
请考虑对您的代码进行以下修改:
#include <stdio.h>
int main(void) {
int num, i, total, average, min, max;
// open file
FILE *ifile = fopen( "scores.txt", "r" );
// if opening file fails, print error message and exit 1
if (ifile == NULL) {
perror("Error: Failed to open file.");
return 1;
}
// initialize i and total to zero.
i = total = 0;
// read values from file until EOF is returned by fscanf,
// or until an error (hence the comparison "== 1")
while(fscanf(ifile, "%d", &num) == 1) {
// In first round of loop, initialize min and max
// to the number being read (num)
// After min/max have been initialized, they can then
// be compared and modified in the second if statement
// in the remaining loop rounds
if (i == 0) {
min = num;
max = num;
total += num;
++i;
continue;
}
if (num < min) {
min = num;
} else if (num > max) {
max = num;
}
total += num;
++i;
}
// initialize average
average = total/i;
// summary
printf("The sum of all integers in file is %d.\n", total);
printf("The number of integers in file is %d.\n", i);
printf("The average of all integers in file is %d.\n", average);
printf ("The minimum is %d\n", min);
printf ("The maximum is %d\n", max);
fclose(ifile);
return 0;
}