gpt4 book ai didi

c - 在 C 中显示最大值和最小值

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:02 25 4
gpt4 key购买 nike

我在显示最低平均值时遇到问题。我做了一个终止值来结束考试分数的输入。当我触发 -999 并显示最低考试分数时,我收到的是 -999 的值,而不是实际的最低分数。我如何排除这个值?

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
int menuChoice, scoreCount = 0;
float examScore = 0.0,
maxScore = 0.0,
minScore = 0.0,
avgScore = 0.0,
sumScore = 0.0;

printf("************************************\n");
printf("1-> Enter an Exam Score\n");
printf("2-> Display the highest exam score\n");
printf("3-> Display the lowest exam score\n");
printf("4-> Display the average exam score\n");
printf("5-> Quit the program\n");
printf("************************************\n\n");

printf("Select a number that corresponds to the menu :\n");
scanf("%d", &menuChoice);

while(menuChoice != 5)
{
switch(menuChoice)
{
case 1:
while(examScore != -999)
{
printf("Enter an exam score (enter -999 to quit score input):\n");
scanf("%f", &examScore);
printf("The score you've entered equates to : %.2f\n\n", examScore);
scoreCount++;

if(maxScore < examScore)
{
maxScore = examScore;
}
if(minScore > examScore)
{
minScore = examScore;
}
else if(examScore < 0 || examScore > 100)
{
printf("Exam Scores range from 0.0 - 100.0\n");
}
sumScore += examScore;
avgScore = sumScore / scoreCount;
}
break;

case 2:
printf("The highest exam score is : %.2f\n", maxScore);
break;

case 3:
printf("The lowest exam score is : %.2f\n", minScore);
break;

case 4:
printf("The average exam score is : %.2f", avgScore);
break;

default:
printf("You've entered an invalid menu choice, review more carefully!");
break;
}

printf("Select a number that corresponds to the menu :\n");
scanf("%d", &menuChoice);
}

system("pause");
return 0;
}

最佳答案

修复 while 循环的逻辑。你更新minScore在查看是否examScore之前是-999,所以这不好。

您还应该初始化变量,例如 examScore在使用它们之前,您不应该像 examScore != -999 这样进行精确比较与花车。要么更改为整数,要么进行更宽容的比较,例如 examScore < -998 .

关于c - 在 C 中显示最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10807807/

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