查找最小值和最大值

use*_*r01 0 c max min

我正在尝试编写一个简单的程序,从数据文件中读取整数并输出最小值和最大值.输入文件的第一个整数将指示将读取多少个整数,然后将列出整数.

我的程序编译没有任何问题,但是,它返回的值不是我的测试数据文件中的集合的一部分.任何人都可以帮助诊断这个问题吗?

int main(){
FILE *fp = fopen("data.txt", "r");
int count;
int num;
int i;
int min = 0;
int max = 0;

fscanf (fp, "%d", &count);

for (i = 0; i < count; i++)
    fscanf( fp, "%d", &i);  
    {   
    if (num < min)
        min = num;
    if (num > max)
        max = num;
    }
fclose (fp);

printf("Of the %d integers, the minimum value is %d and the maximum value is %d \n", count, min, max);} 
Run Code Online (Sandbox Code Playgroud)

hal*_*elf 5

以下是代码中的几个错误.

首先,如cnicutar所说,改变inum循环中fscanf.这样您就可以正确读取输入.并且左括号{应该在for循环之后.

for (i = 0; i < count; i++)  {   // put the { here
    fscanf( fp, "%d", &num);
Run Code Online (Sandbox Code Playgroud)

其次,你的minmax没有正确启动.你应该把它们变成INT_MAXINT_MIN.并且#include <limits.h>.

#include <stdio.h>
#include <limits.h>
......
int min = INT_MAX;
int max = INT_MIN;
Run Code Online (Sandbox Code Playgroud)