此声明
max = min = num;
没有意义,因为变量num
没有初始化。
您的意思是以下内容。我想分数不能为负数。
#include <stdio.h>
int main()
{
unsigned int n;
printf( "Number of Students: " );
scanf( "%u",&n );
unsigned int min = 0,max = 0,count_min = 0,count_max = 0;
unsigned int sum = 0;
for ( unsigned int i = 0; i < n; i++ )
{
printf("Students no: %u\n",i + 1 );
printf("Score: ");
unsigned int num;
scanf( "%u",&num );
sum += num;
if ( i == 0 || max < num )
{
max = num;
count_max = 1;
}
else if ( !( num < max ) )
{
++count_max;
}
if ( i == 0 || num < min )
{
min = num;
count_min = 1;
}
else if ( !( min < num ) )
{
++count_min;
}
}
float average = n == 0 ? 0.0f : ( float )sum / n;
printf( "Average score is %3.1f\n",average );
printf( "The highest score is %u that is had by %u student(s)\n",max,count_max );
printf( "The lowest score is %u that is had by %u student(s)\n",min,count_min );
return 0;
}
程序输出看起来像
Number of Students: 6
Students no: 1
Score: 1
Students no: 2
Score: 4
Students no: 3
Score: 3
Students no: 4
Score: 2
Students no: 5
Score: 1
Students no: 6
Score: 3
Average score is 2.3
The highest score is 4 that is had by 1 student(s)
The lowest score is 1 that is had by 2 student(s)
,
在此行上
max = min = num;
将所有这些值设置为相同。但是num
尚未初始化,因此这是未定义的行为。然后可能发生任何事情-该程序很可能会继续使用三个变量的垃圾值。相反,请删除此行并按如下所示初始化变量:
int i,n,sum = 0,num = 0,min = INT_MAX,max = INT_MIN;
可以将
min
设置为最高有效输入。通常,您可以将其从INT_MAX
设置为<limits.h>
,以将其设置为最大可能值。对于max
和INT_MIN
也是如此。
本文链接:https://www.f2er.com/3116635.html