我正在创建一个程序,让我输入 1-50 的 6 个年级,并让它给我总分和分数的百分比。我遇到的唯一麻烦是,当 if 循环激活时,它不会返回到上一个输入,而是跳到下一个输入。我该如何使其返回到之前的输入以便可以重新输入?
#include <stdio.h>
int main() {
int percent;
int totalscore;
const int score[5];
for (int grades = 1; grades <= 6; grades++) {
printf("please enter the grade for assignment #%d: ", grades);
scanf("%d", &score[grades]);
if (score > 0 , score > 51);
printf("Please enter a number between 1 and 50\n");
}
totalscore = score[1] + score[2] + score[3] + score[4] + score[5] + score[6];
printf("Over 6 assignments you earned %d points out of a possible 300 points!\n", totalscore);
percent = totalscore / 3 ;
printf("Your grade is %d percent.", percent);
return 0;
}
在这段代码中,您犯了两个错误。第一个是您使用分号“;”在“if”语句的末尾,第二个是您在“if”条件中使用了“,”,这是不正确的。 您可以看到下面的更正:-
if (score <= 0 || score >= 51)
printf("Please enter a number between 1 and 50\n");
我可以在输入部分本身看到一些初学者的缺陷。
if 条件不正确。 - 您想要检查在特定索引处输入的输入值,而不是整个数组。另外,您通过给出
;
来关闭 if 条件,这会破坏该场景。
我已经更新了代码。
#include <stdio.h>
int main() {
int percent;
int totalscore;
const int score[5];
for (int grades = 1; grades <= 6; grades++) {
printf("please enter the grade for assignment #%d: ", grades);
scanf("%d", & score[grades]);
// updated if condition.
if (score[grades] < 1 || score[grades] > 50) {
printf("Please enter a number between 1 and 50\n");
grades--;
}
}
totalscore = score[1] + score[2] + score[3] + score[4] + score[5] + score[6];
printf("Over 6 assignments you earned %d points out of a possible 300 points!\n", totalscore);
percent = totalscore / 3;
printf("Your grade is %d percent.", percent);
return 0;
}
编辑-
更新条件以仅接受 1-50 的输入。谢谢 @ 乔纳森·莱夫勒