gpt4 book ai didi

c - 简单的C语言代码问题

转载 作者:太空宇宙 更新时间:2023-11-04 03:54:40 24 4
gpt4 key购买 nike

我目前正在练习 C 语言,并且在使用简单的基本编码计算学校科目的平均分数时遇到了问题。

代码如下:

#include <stdio.h>
int main()
{
int a;
int sub, score;
float totalscore = 0;

printf("How many subjects to average? - 8 or less subjects - \n");
scanf("%d", &sub);

if(sub > 8)
{
printf("number of subjects cannot be more than 8 \n");
}

printf("Enter score for each subjects \n");
for(a =1;a <= sub;a++)
{
printf("Subject %d : ", a);
scanf("%d", &score);
totalscore = totalscore + score;
}

printf("Total %d number of subjects' average is %.2f", sub, totalscore/sub);

return 0;
}

如果有人输入他们希望平均的科目数量,它会继续说“输入每个科目的分数”,他们将能够输入每个科目的分数。

所以我的问题是,如果输入的科目数量超过 8 个,您如何让程序不继续?就呆在那里但是,显示“主题的数量不能超过 8”?

我认为这是一个非常简单的问题,但我不知道如何表达这个问题以便在 Google 上搜索。

提前致谢。

最佳答案

如果您想让用户再试一次,您可以将获取主题数量的代码放入一个循环中,该循环一直持续到用户输入有效数字为止。

sub = 9;
while (sub > 8 || sub < 1)
{
printf("How many subjects to average? - 8 or less subjects - \n");
scanf("%d", &sub);

if (sub > 8)
{
printf("number of subjects cannot be more than 8\n");
}
else if (sub < 1)
{
printf("number of subjects cannot be less than 1\n");
}
}

关于c - 简单的C语言代码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17605332/

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