【发布时间】:2014-03-12 23:10:31
【问题描述】:
我正在为我的一门课程编写代码,但我碰壁了。我需要用户输入一个数字,该数字将用作重复 for 循环的次数。我要求这个数字的第一个循环是一个 while 循环。我需要确保输入的值是数字而不是字母或特殊字符。
我不知道如何确定它不是字母或特殊字符。
下一个问题是确保 for 循环只运行指定的次数,即第一个循环中提供的次数。
这是我到目前为止所写的。
#include <stdio.h>
int main()
{
int num_of_scores, n;
char enter;
float score=-1, total=0, average;
do
{
printf("\n\nEnter the number of quiz scores between 1 and 13: ");
scanf ("%d, %c", &num_of_scores, &enter);
}
while(num_of_scores<1 || num_of_scores>13/* && enter == '\n'*/);
printf("\nStill Going!");
for(n=0; n<num_of_scores; n++)
{
printf("\nEnter score %i: ", n+1);
scanf ("%f", &score);
while(score>=0 || score<=100)
{
total = total + score;
score = -1;
break;
}
}
average = total / num_of_scores;
printf("\nThe average score is %.0f.\n\n", average);
return 0;
}
所以我稍微编辑了代码。第一个 while 循环中有一部分在我删除的注释中,因为它使程序在该循环之后结束。 printf("still going") 只是一个测试,以确保程序能走得那么远。任何进一步的指示?我仍然不确定如何检查以确保未输入数字。我虽然添加 && enter == '\n' 会这样做,但如果它挂起程序那就不好了。您建议的许多示例都很好,但我发现它们有点令人困惑。谢谢!
【问题讨论】:
-
您应该在使用前将值初始化为 0。 num_of_scores 有可能包含垃圾值。
-
约翰 我相信我解决了这个问题。我有吗?