请帮我解决这个明显愚蠢的错误
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctime>
int main()
{
srand((unsigned)time(NULL));
int No_of_Q = 0; //number of questions
int m1, m2, ans; //two operands and answer
int ra = 0; //number of right answers
int wa = 0; //number of wrong answers
char c = 'y'; //whether to continue
printf("Let's play multiply!\n");
do
{
printf("How many questions would you like to attempt? ");
scanf_s("%d", &No_of_Q);
printf("\n");
for(int i=1; i<=No_of_Q; i++)
{
m1=(rand()%10 + 1);
m2=(rand()%10 + 1);
printf("\nWhat is %d x %d = ", m1, m2);
scanf_s("%d",&ans);
if(ans== m1*m2)
{
printf("Your answer is correct!\n");
ra++ ;
}
else{
printf("Wrong, the correct answer is %d.\n", m1*m2);
wa++ ;
}
}
printf("\n\nOut of %d answers, %d were correct and %d wrong.\n",No_of_Q, ra, wa);
if(wa==0)
printf("Congratulations!\n");
else
printf("Better luck next time!\n");
printf("Continue game? ");
scanf_s("%c", &c ); /*-------CANNOT GET THIS TO PERFORM--------------*/
//printf("%c",c);
}
while(c=='y');
return 0;
}
我使用的是 vs 2012 Express 版本。 我无法让我的程序扫描答案以在程序结束时继续。 最后的 while 语句不进行计算。 请帮忙。
最佳答案
问题是你的行 scanf_s("%d", &ans);
读取数字后的换行符,但不包括换行符。 scanf_s("%c", &c);
然后读取换行符,它不是 'y'
,因此循环失败。
这就是为什么你会发现很多人(包括我自己)推荐阅读 fgets()
的回复。然后用 sscanf_s()
转换输入.
您还应该检查 scanf_s()
返回正确的值(提到的两个调用为 1)——或者 fgets()
和sscanf_s()
返回正确的值( fgets(line, sizeof(line), stdin) != 0
和 sscanf_s(...) == 1)
)。
您还应该注意 #include <ctime>
是 C++ 头文件; C header 是 #include <time.h>
。我没有看到#include <conio.h>
有任何用处,所以你可以省略它。
此外,您打错了 scanf_s()
当使用%c
时转换。如BluePixy在 comment 中指出,您应该在 &c
之后传递长度 1 :
if (scanf("%c", &c, 1U) != 1)
...oops...
C11 (ISO/IEC 9899:2011) 附录 K 涵盖了边界检查接口(interface),内容大致相同。
关于c - c语言新手,我的代码有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18171563/