做作业遇到问题,求各位帮忙
题目:
小学生 100 以内整数加减乘除运算训练。程序随机产
生两个 100 以内的正整数 a 和 b 和一个运算符(+、-、*、/),小学生计算并输入结果。
要求如下:
① 程序应该显示运算式子,并给出小学生运算是否正确的判断信息;
② 可以进行多轮运算,一轮中包括多道题(例如10道题);每出一题,学生回答运算结果,
程序给出对错判别;每轮运算完成后程序给出答题的总结果,并询问是否进行下一轮的
训练,以决定是否继续;
③ 要保证减法运算时不出现负数,除法运算时被除数能整除除数;
④ 操作界面友好。
代码:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int a,b,answer,operator,correct,t,i,x,y,n;
char ch;
i=0;
x=0;
y=0;
n=1;
srand(time(NULL));
printf("输入Y开始");
ch=getchar();
while(ch!='N')
{
while(i<10)
{
a=rand()%100+1;
b=rand()%100+1;
operator=rand()%4;
if(a<b)
{
t=a;
a=b;
b=t;
}
if(operator==0)
{
printf("(%d) %d+%d=? ",n,a,b);
correct=a+b;
n++;
}
else if(operator==1)
{
printf("(%d) %d-%d=? ",n,a,b);
correct=a-b;
n++;
}
else if(operator==2)
{
printf("(%d) %d*%d=? ",n,a,b);
correct=a*b;
n++;
}
else if(operator==3)
{
while(a%b!=0)
{
a=rand()%100+1;
b=rand()%100+1;
}
printf("(%d) %d/%d=? ",n,a,b);
correct=a/b;
n++;
}
printf("输入答案:");
scanf("%d",&answer);
if(correct==answer)
{
printf("正确\n");
x=x+1;
}
else
{
printf("错误\n");
y=y+1;
}
i++;
}
printf("一共对%d道,错%d道",x,y);
printf("时候还要继续?输入Y继续,N结束:\n");
ch=getchar();
}
return 0;
}
运行:
因为前面 scanf("%d",&answer); 用户输入了数据和换行符‘\n’,在读取了数据之后,输入缓存里就残留了一个‘\n’。
再次使用ch=getchar();会读取输入缓存里上次残留的‘\n’,而不是读取新输入的字符。这样就造成了严重的错误。
可以在用 ch=getchar(); 读取字符前用 setbuf(stdin, NULL); 清除输入缓存。
setbuf(stdin, NULL);
ch=getchar();
或者用 scanf("%1s",&ch); 读取字符,用"%1s"会跳过空格与换行符,读取一个非空格与换行符的字符。
再有
i=0;
x=0;
y=0;
n=1;
这四个变量设置初值应该放在外层 while循环内。这样在作完10道题目之后,要继续作题时这四个变量重新恢复为初值,重新计数。
如果这四个变量设置初值放在while循环之前。在作完10道题目之后,要继续作题时这四个变量不会重新恢复为初值,i还是10,就不会再循环了。
你题目的解答代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int a,b,answer,operator,correct,t,i,x,y,n;
char ch;
srand(time(NULL));
printf("输入Y开始");
ch=getchar();
while(ch!='N')
{
i=0;
x=0;
y=0;
n=1;
while(i<10)
{
a=rand()%100+1;
b=rand()%100+1;
operator=rand()%4;
if(a<b)
{
t=a;
a=b;
b=t;
}
if(operator==0)
{
printf("(%d) %d+%d=? ",n,a,b);
correct=a+b;
n++;
}
else if(operator==1)
{
printf("(%d) %d-%d=? ",n,a,b);
correct=a-b;
n++;
}
else if(operator==2)
{
printf("(%d) %d*%d=? ",n,a,b);
correct=a*b;
n++;
}
else if(operator==3)
{
while(a%b!=0)
{
a=rand()%100+1;
b=rand()%100+1;
}
printf("(%d) %d/%d=? ",n,a,b);
correct=a/b;
n++;
}
printf("输入答案:");
scanf("%d",&answer);
if(correct==answer)
{
printf("正确\n");
x=x+1;
}
else
{
printf("错误\n");
y=y+1;
}
i++;
}
printf("一共对%d道,错%d道",x,y);
printf("时候还要继续?输入Y继续,N结束:\n");
setbuf(stdin, NULL);
ch=getchar();
}
return 0;
}
如有帮助,望采纳!谢谢!
因为73行用getchar接收字符时,除了输入的字符,还有一个回车符,所以在73行下面,需要再加一句getchar();