我是C语言初学者。我得到了这个潜水分数计划的任务。规则是分数必须在0到10之间,如果分数无效,程序应该要求新分数,并且应该有至少4名裁判给出分数。 我对使用for循环的部分有问题,我希望程序继续检查分数是否无效,但我无法重复for循环。请帮帮我,这是我的代码。
for (index = 0; index < judges; index++)
{
printf ("Enter the score for judges #%d(1-10): ", index + 1);
scanf ("%f", &score[index]);
if ((score[index] >= 0) && (score[index] <= 10))
{
totalscore += score[index];
}
else
{
totalscore = 0;
for (index = 0; index < judges; index++)
{
printf ("11111Enter the score for Judges #%d(0-10): ", index + 1);
scanf ("%f", &score[index]);
if ((score[index] >= 0) && (score[index] <= 10))
{
totalscore += score[index];
return EXIT_SUCCESS;
}
答案 0 :(得分:1)
使用此模式:
do
{
prompt();
scanf(&variable);
}
while (is_invalid (variable));
这样,您只需要在一个地方检查变量是否有效,而只需要在一个地方提示。
您的多个while
和if
容易出错且无法正确使用。
所以而不是:
printf ("Enter the number of judges (must bewteen 4-8): ");
scanf ("%d", &judges);
if ((judges < 4) || (judges > 8)){
while (true) {
printf ("\ninvaild number of judges\n\nEnter the number of judges (must between 4-8): ");
scanf ("%d", &judges);
if ((judges >= 4) && (judges <= 8)) {
break;
}}}
使用:
do
{
printf ("\n\nEnter the number of judges (must between 4-8): ");
scanf ("%d", &judges);
}
while ((judges < 4) || (judges > 8));
答案 1 :(得分:0)
为什么在内部for循环中使用相同的变量“index”?它会搞砸一切。假设你有4个评委,你输入了3和5.你试图输入17,现在指数是2,对吧?但得分是invald,所以它会转到“else {xxxxx}”,这里你有一个内部for循环“for(index = 0; index&lt; judge; index ++)”,所以变量“index”回到0! IMO在这种情况下,“while”更好:
while ((score[index] < 0) || (score[index] > 10))
printf(xxxxxxx)
scanf(xxxxxxx)
如果你真的需要多个for循环,你应该使用不同的变量:
for (i=0; i<judges; i++)
/*DO STH*/
for (j=0; j<judges; j++)
/*DO STH*/
for (k=0; k<judges; k++)
/*DO STH*/
答案 2 :(得分:0)
查看你的代码,我相信你的问题不是理解C中的“for”循环,而是在接近代码之前构建正确的程序流程(如果你愿意,你的“算法”)。
练习伪代码:
For Each Judge:
Continue to ask for score until it is valid
或者你可以进一步细分:
Beginning of loop:
Current Judge = 0
current Score = invalid
Do this while score is invalid
ask score of current judge.
Increment Current Judge
Unless no more judges, go to beginning of loop