gpt4 book ai didi

c - 如何修复我的最大输出以及如何添加最大和最小数量

转载 作者:行者123 更新时间:2023-11-30 14:34:49 26 4
gpt4 key购买 nike

这是我的代码:

#include <stdio.h>

int main()
{
float average;
int i, n, sum = 0, num, min, max;

printf("Number of Students: ");
scanf("%d", &n);

max = min = num;

for (i = 1; i < (n + 1); i++) {
printf("Students no: %d\n", i);
printf("Score: ");
scanf("%d", &num);

if (num > max) {
max = num;
}

if (num < min) {
min = num;
}

sum = sum + num;
}

average = 1.0*sum/n;

printf("Average score is %.2f\n", average);
printf("The highest score is %d\n", max);
printf("The lowest score is %d\n", min);

return 0;
}

问题是我的最大输出总是错误的,而且我不知道我的错误。如何添加获得最高分和最低分的学生人数?

最佳答案

本声明

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)

关于c - 如何修复我的最大输出以及如何添加最大和最小数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58820844/

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