[求助]看看这个程序为什么会发生这种意外?
为什么输入非数字时没有按设想的提示"please continue,just type in another data,make sure what you entered is a number between 0~100",而是提示"sorry,what you've just entered exceed the right range of score,please enter a new score between 0~100!",而且在死循环的过程中提示输入SCORE 1时我没有任何输入信息它都会自动执行后续的printf()语句.(请注意:图2的每一个SCORE 1的冒号后面都是空的,没有进行任何输入)如果说在运行的时候它是先把非数字输入转换为整型然后再参与运算,那为什么当输入大于100的数字时,没有陷入死循环,而输入非数字时会陷入死循环呢,而且没有任何后续输入都能自行无穷循环?该如何解决这个问题,如何达到设想的良好交互的目的?
程序及运行结果如下:
/*program to calculate the average of a set of grades and count the number of failing test grades */
#include <stdio.h>
main (void)
{
int grades,sum=0,grade_counter=1,failures=0,excellent=0;
float average;
char end_flag;
printf ("please enter the scores one by one!\n");
do
{
printf ("score %i: ",grade_counter);
scanf ("%i",&grades);
if (grades>=0 && grades<=100)
{
printf ("%i\n",grades);
sum=sum+grades;
grade_counter++;
if (grades<75)
failures++;
else
excellent++;
}
else if (grades<0 || grades>100)
printf ("\nsorry,what you've just entered exceed the right range of score,please enter a new score between 0~100!\n\n");
else
{
printf ("you've just entered a non-number,do you want to end entering? (Y/N)");
scanf ("%c",&end_flag);
{
if (end_flag=='y')
break;
else
printf ("please continue,just type in another data,make sure what you entered is a number between 0~100");
}
}
}
while (end_flag != 'y');
average=(float) sum/grade_counter;
printf("The average score is: %f\n\n",average);
printf("and there are %i failures.",failures);
getch();
return 0;
}
输入数字时运行结果:
输入字母时运行结果:
[此贴子已经被作者于2007-9-30 14:56:02编辑过]