[英]Maximum and minimum number from a file in C
我有一个文件,其中包含用空格分隔的数字,然后输入。 我想找到最大和最小:
#include <stdio.h>
#include <conio.h>
int main()
{
char nums[500];
int min,max,i,a;
FILE * file;
file = fopen ("test.txt", "r");
i=0;
while( fscanf(file, "%d,", &a) > 0 )
{
nums[i++] = a;
}
for(i=0; i<=sizeof(nums); i++){
if (nums[i]>max) max=nums[i];
if (nums[i]<min) min=nums[i];
}
printf("Maximum: %d\n", max);
printf("Minimum: %d", min);
fclose (file);
getch();
}
我总是得到:
Maximum: 2686820
Minimum: -128
好的,所以我将char nums[500]
更改为int nums[500]
。 我初始化了max=0
和min=INT_MAX
(使用<limits.h>
)。 它仍然给我一个随机值。
如果文件中的数字更改,我将如何处理? 有没有一种方法可以使用文件中数字的特定长度来初始化数组?
您无需初始化min
和max
变量。 未初始化的非静态局部变量(例如您的min
和max
变量)具有不确定的值,实际上,它们似乎是随机的。 在没有初始化的情况下使用它们会导致不确定的行为 。
您还没有初始化所有的数组,这意味着你没有初始化值也将有不确定的值。
而且,为了增加侮辱性伤害,您还超出了数组的范围,这也导致未定义的行为。
哦,而且如果您从文件中读取的值大于char
,它将被截断。
此外,您将从文件中读取的int
值存储在char
数组中,从而降低了精度。
您盲目地认为该文件包含的号码不超过500个-对吗? 您盲目地认为文件中的数字适合char范围-这是正确的吗?
然后for循环中的sizeof(nums)总是返回500,那么如果文件实际包含的数字少于500,会发生什么呢? 您访问尚未初始化或包含垃圾的内存。
然后,您无需初始化min和max,它们也将使用当时在内存中当前找到的值进行初始化。
(哇,我没有看到其他答案的提示...)
除了其他文章,这是解决您的问题的解决方案(应检查fscanf
的返回值,并添加一些错误
int min,max,i,a;
FILE * file;
file = fopen ("test.txt", "r");
fscanf(file, "%d,", &a);
min = max = a;
while( fscanf(file, "%d,", &a) > 0 )
{
if (min > a) min = a;
if (max < a) max = a;
}
而且,你提到
一个包含以空格隔开的数字的文件, 然后输入 。
因此,您必须编写fscanf(file, "%d", &a);
而不是fscanf(file, "%d,", &a);
这意味着您必须在格式化的字符串中用空格替换逗号。
the following code corrects the problems,
compiles cleanly,
demonstrates a proper error handling technique
eliminates the portability problem
eliminates unneeded variables
because a space is part of the 'white space' definition and
the %d input conversion format specifier skips over white space,
so no extra spacing in the scanf format string.
#include <stdio.h>
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <limits.h> // INT_MAX, INT_MIN
int main()
{
int min = INT_MAX;
int max = INT_MIN;
int a; // current value read from file
FILE * file = NULL;
if( NULL == (file = fopen ("test.txt", "r") ) )
{ // then, fopen failed
perror( "fopen for test.txt failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
while( fscanf(file, "%d", &a) )
{
if( a < min ) min = a;
if( a > max ) max = a;
} // end while
printf("Maximum: %d\n", max);
printf("Minimum: %d\n", min); // '\n' causes output to terminal
fclose (file);
getchar();
return( 0 );
} // end function: main
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.