#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」,而不是再次提示相同問題的用戶,然後正確掃描它只是跳入一個無限循環。我想知道如何解決這個問題。
感謝
無效輸入時清除輸入緩衝區。 – BLUEPIXY
當你使用'scanf(「%d」,&value)掃描一個整數'並且輸入不是一個有效整數時,'scanf'返回0並且輸入返回到它開始的位置,即在非數字輸入。隨後的調用將嘗試重新解析相同的無效輸入。你應該'scanf(「%* s」)'跳過它。更好的方法是,用'fgets'和'sscanf'將整行讀入它們中。 –
我不明白爲什麼會使用輸入'-9876'? – ameyCU