gpt4 book ai didi

c - 查找最小值和最大值

转载 作者:太空宇宙 更新时间:2023-11-04 05:29:12 24 4
gpt4 key购买 nike

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

我的程序编译没有任何问题,但是,它返回的值不属于我的测试数据文件中的集合。谁能帮助诊断这个问题?

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);}

最佳答案

您的代码中有几个错误。

首先,改变inumfscanf 的循环中正如cnicutar所说。以便您可以正确读取输入。和左括号{应该在 for 之后循环。

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

其次,你的minmax未正确启动。您应该将它们更改为 INT_MAXINT_MIN .和 #include <limits.h> .

#include <stdio.h>
#include <limits.h>
......
int min = INT_MAX;
int max = INT_MIN;

关于c - 查找最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12575856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com