我是编程的新手,我正在尝试完成一项编程练习,在该练习中,老师(用户)将输入成绩,并不断提示他们输入成绩,直到他们输入“ -1”为止。输入后,提示将结束,并且应该输出所有用户输入的成绩的平均值,以及输入的最高和最低成绩。
这是我到目前为止的代码。
#include <stdio.h>
int main()
{
unsigned int counter;
float average;
int grade, total, max, min;
total=0;
counter=0;
max=100;
min=0;
printf("Please enter grades, enter -1 to stop\n");
scanf ("%d", &grade);
max=min=grade;
while ( grade !=-1 ) {
total = total+ grade;
counter= counter +1;
if (grade > max)
max = grade;
if (grade < min)
min = grade;
printf("Please enter grades, enter -1 to stop\n");
scanf ("%d", &grade);
max=min=grade;
}
if ( counter !=0 ) {
average = (float) total / counter;
printf("Your average is %.2f\n",average);
printf("Your highest grade is %d\n", max);
printf("Your lowest grade is %d\n", min);
}
else {
printf("No grades were entered\n");
}
}
以下是示例代码的输入结果:
Please enter grade, enter -1 to stop
95
Please enter grade, enter -1 to stop
87
Please enter grade, enter -1 to stop
-1
Your average is 91.00
Your highest grade is -1
Your lowest grade is -1
我不知道为什么它不能显示正确的值,在这种情况下,最高为95,最低为87。我将不胜感激,因为它是我需要解决的程序的唯一部分。
谢谢。
答案 0 :(得分:1)
在while循环中,您第二次在程序中提到 min = max = grade 。 那就是从用于停止程序的等级取-1的值。 请注释该行并尝试使用。
答案 1 :(得分:0)
这里:
#include <stdio.h>
int main()
{
unsigned int counter;
float average;
int grade, total, max, min;
total=0;
counter=0;
max=100;
min=0;
printf("Please enter grades, enter -1 to stop\n");
scanf ("%d", &grade);
max=min=grade;
while ( grade !=-1 )
{
total = total+ grade;
counter= counter +1;
if (grade > max)
{
max = grade;
}
if (grade < min)
{
min = grade;
}
printf("Please enter grades, enter -1 to stop\n");
scanf ("%d", &grade);
}
if ( counter !=0 )
{
average = (float) total / counter;
printf("Your average is %.2f\n",average);
printf("Your highest grade is %d\n", max);
printf("Your lowest grade is %d\n", min);
}
else
{
printf("No grades were entered\n");
}