正如我的项目所述,我需要创建一个程序来读取文件并找到文件中最大和最小值中的2个。这是我的程序,它似乎找到了最大和最小,但确实得到了第二大和最小。两个小和两个大的fscanf
似乎没有从文件中获取值,因此我也得到了答案的随机值。我不知道什么是错的,如果你能告诉我什么是错的那就太棒了。
#include <stdio.h>
int
main (void)
{
FILE *in; /*names the file*/
int onesmall, twosmall, compare, onebig, twobig;
in = fopen("file2.data", "r"); /*opening the file*/
fscanf(in,"%d", &onesmall); /*scans and inputs first value (lowest value as of now)*/
fscanf(in,"%d", &onebig);
fscanf(in,"%d", &twobig);
fscanf(in,"%d", &twosmall);
while(!feof(in)){ /*loops till reaches to end of file*/
fscanf(in,"%d", &compare); /*scans and inputs first value*/
if (compare <= onesmall){
onesmall = compare; /*checks if value in compare is smaller than value in onesmall if it is then it will relace it*/
}
if (compare >= onebig){
onebig = compare; /*checks if value in compare is greater than value in onebig if it is then it will relace it*/
}
}
while(!feof(in)){
fscanf(in,"%d",&compare);
if (compare <= twosmall && compare != onesmall){ /*if value in compare is smaller than twosmall and not eaual to onsmall replace it*/
twosmall = compare;
}
if(compare >= twobig && compare != onebig){ /*if value in compare is greater than twobig and not eaual to onebig replace it*/
twobig = compare;
}
}
printf("The lowest value in the file is: %d\n", onesmall);
printf("The second lowest value in the file is: %d\n", twosmall);
printf("The greatest value in the file is: %d\n", onebig);
printf("The second greatest value in the file is: %d\n", twobig); /*prints output*/
fclose(in);
return (0);
}