c新手,我的代码怎么了
请帮我解决这个明显愚蠢的错误c新手,我的代码怎么了,c,scanf,C,Scanf,请帮我解决这个明显愚蠢的错误 #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
#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;
}
#包括
#包括
#包括
#包括
int main()
{
srand((无符号)时间(NULL));
int No_of_Q=0;//问题数量
int m1,m2,ans;//两个操作数和答案
int ra=0;//正确答案的数目
int wa=0;//错误答案的数量
char c='y';//是否继续
printf(“让我们玩乘法!\n”);
做
{
printf(“您想尝试多少个问题?”);
scanf_s(“%d”和“没有”个);
printf(“\n”);
对于(int i=1;i而言,问题在于您的行scanf_s(“%d”,&ans)
最多读取但不包括数字后面的换行符。scanf_s(“%c”,&c);
然后读取不是'y'
的换行符,因此循环失败
这就是为什么许多人(包括我自己)建议用fgets()
阅读响应,然后用sscanf\u s()转换输入
您还应该检查scanf_s()
是否返回正确的值(对于所提到的两个调用为1)-或者fgets()
和sscanf_s()
是否返回正确的值(fgets(line,sizeof(line),stdin)!=0
和sscanf_s(…)=1)
)
<>你也应该注意,<>代码>包含/c>是C++头;C标题是“代码>”,包含。我看不出任何用法< <代码> >包含< /C> >,这样你就可以省略。
此外,在使用%c
转换时,您正在错误调用。正如在a中指出的,您应该在&c
之后传递长度1:
if (scanf("%c", &c, 1U) != 1)
...oops...
C11(ISO/IEC 9899:2011)附录K涵盖了边界检查接口,说明大致相同。使用scanf_s(“%c”、&c);
函数两次而不是一次。第一次将获得'\n'
字符,然后它将被您的输入替换
printf("Continue game? ");
scanf_s("%c", &c ); /*-------WILL GET '\n'--------------*/
scanf_s("%c", &c ); /*-------WILL ASK FOR INPUT--------------*/
首先,您的问题不清楚。您需要发布错误。这就是没有人试图为您提供解决方案的原因。例如,请参阅许多类似问题中的一个。请参阅scanf_s
需要%s
,%c
例如scanf_s(“%c”,&c,1)
标题很不清楚,尝试修改它以反映问题。那么,解决方案是什么?我已经告诉过你我将使用的解决方案:使用fgets()
读取一行输入,然后使用sscanf_()
转换输入。在使用结果之前,我会错误地检查输入。