【发布时间】:2015-12-21 02:46:18
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int main(int argc, char * argv[])
{
printf("This program tests your integer arithmetic skills.\n"
"You should answer the questions following the same \n"
"rules that computers do for integers arithmetic, not \n"
"floating-point arithmetic. Hit the 'Enter' key after \n"
"you have typed in your input. When you wish to finish \n"
"the test, enter -9876 as the answer to a question.\n"
"\n");
int n1, n2, answer, user_answer, a, b, int_per;
char op, c;
float per, count, count_r, count_w;
count = 0;
count_r = 0;
count_w = 0;
printf("What is your question? ");
scanf("%d %c %d", &n1, &op, &n2);
do
{
count++;
printf("What is %d %c %d ? ", n1, op, n2);
if (op == '+')
{
answer = n1 + n2;
}
else if (op == '-')
{
answer = n1 - n2;
}
else if (op == '%')
{
answer = n1 % n2;
}
else if (op == '/')
{
answer = n1 / n2;
}
else if (op == '*')
{
answer = n1 * n2;
}
c = scanf("%d", &user_answer);
if (user_answer == answer)
{
printf("Correct!\n\n");
count_r++;
}
else if (user_answer == -9876)
{
count = count - 1;
break;
}
else if (c != 1)
{
printf("Invalid input, it must be just a number\n\n");
printf("What is %d %c %d ? ", n1, op, n2);
}
else if (user_answer != answer)
{
printf("Wrong!\n\n");
count_w++;
}
} while(user_answer != -9876);
per = (count_r / count) * 100;
a = (int) count_r;
b = (int) count_w;
int_per = roundf(per);
printf("\nYou got %d right and %d wrong, for a score of %d%c\n", a,
b, int_per, 37);
return EXIT_SUCCESS;
}
上面的代码应该循环询问问题和答案,直到用户输入 -9876 作为答案,然后程序终止并给他们分数。这一切都有效,除了!!一方面。当用户在输入中输入非数字时。发生这种情况时,它应该说“输入无效,请重试”,然后再次询问相同的问题。例如
你的问题是什么? 9+9
什么是 9 + 9? 嗯,8
输入错误,请重试
什么是 9 + 9?
SO.. 用户输入了“hmmm”,而不是再次提示用户相同的问题,然后正确扫描,它只是跳入了一个无限循环。我想知道如何解决这个问题。
谢谢
【问题讨论】:
-
输入无效时清除输入缓冲区。
-
当您使用
scanf("%d", &value)扫描整数并且输入不是有效整数时,scanf返回 0 并且输入返回到它开始的位置,即在非数字输入之前。随后的调用将尝试一遍又一遍地重新解析相同的无效输入。你应该scanf("%*s")跳过它。更好的是,将带有fgets和sscanf的整行读入其中。 -
我不明白为什么要使用输入
-9876? -
您在 scanf 函数中使用了 %d %c %d 之间的空格..将垃圾值分配到 &n1、&op、&n2 变量中
-
@NeErAjKuMaR:不,它没有;格式字符串中的空格只是告诉
scanf跳过空白字符。
标签: c while-loop infinite-loop