设计一个程序,用来实现帮助小学生进行算术运算练习,它具有以下功能:
(1) 提供10道加、减、乘、除四种基本算术运算的题目,每道题中的操作数是随机产生的;
(2) 加减是100以内的数;乘除为乘法表里的;被减数大于减数;除法要求能整除;被乘数小与乘数;(若不合格重新产生)
(3) 练习者根据显示的题目输入自己的答案,程序自动判断输入的答案是否正确并显示出相应的信息。最后显示做对了几道题;
(4) 每次答题要记录做错的题目,下次做题可选择上次做错的题;
#include<iostream>
#include<stdio.h>
#include<cstdlib>
#include<time.h>
#define N 10
using namespace std;
struct math
{
int i;
int a,b;
char op;
int result;
int ans;
bool test;
struct math *next;
};
struct math *creat()
{ int j;
struct math *head, *p1, *p2;
srand(time(0));
head=p2=(struct math *)malloc(sizeof(struct math));
for(int i=0; i<N; i++)
{
j=rand()%4;
p1=(struct math *)malloc(sizeof(struct math));
switch(j)
{
case 1: p1->op='+';
p1->a=rand()%100;
p1->b=rand()%100;
p1->result=p1->a+p1->b;
break;
case 2: p1->op='-';
p1->a=rand()%100;
p1->b=rand()%100;
while(p1->a<p1->b)
p1->a=rand()%100;
p1->result=p1->a-p1->b;
break;
case 3: p1->op='x';
p1->a=rand()%10;
p1->b=rand()%10;
while(p1->a<p1->b)
p1->a=rand()%10;
p1->result=p1->a*p1->b;
break;
default : p1->op='/';
p1->b=rand()%10;
p1->a=(rand()%10)*p1->b;
p1->result=p1->a/p1->b;
break;
}
p2->next=p1;
p2=p1;
}
p1->next=NULL;
return head;
}
void baocun(struct math *head)
{
FILE *fp;
struct math *p;
p=head->next;
if((fp=fopen("tian.txt","w"))==NULL)
{
cout<<"open error"<<endl;
exit(0);
}
else
while(p!=NULL)
{
if(fwrite(p,sizeof(struct math),1,fp)!=1)
printf("error\n");
else
p=p->next;
}
//printf("保存成功!\n");
fclose (fp);
}
struct math *read (struct math *head)
{
FILE *fp;
struct math *p1,*p2;
if((fp=fopen("tian.txt","r"))==NULL)
{
printf("tttttttttttttttttttt\n");
printf("error\n");
exit (0);
}
p2=head=(struct math *)malloc(sizeof(struct math));
p1=(struct math *)malloc(sizeof(struct math));
head->next=p1;
while(fread(p1,sizeof(struct math),1,fp)==1)
{
p2->next=p1;
p2=p1;
p1=(struct math *)malloc(sizeof (struct math));
}
p1->next=NULL;
fclose(fp);
return head;
}
void test()
{
struct math *p,*head;
int i=1;
int x;
int count=0;
cin>>x;
switch(x)
{
case 1: head=creat();
p=head->next;
while(p!=NULL)
{
p->i=i;
cout<<"第"<<p->i<<"道题:"<<p->a<<p->op<<p->b<<"=";
cin>>p->ans;
if(p->ans==p->result)
{
cout<<"正确!"<<endl;
count++;
p->test=true;
}
else
{
cout<<"错误!"<<endl;
p->test=false;
}
p=p->next;
i++;
}
cout<<N<<"道题做对了"<<count<<"道"<<endl;
baocun(head);
break;
case 2:
head=read(head);
p=head->next;
while(p!=NULL)
{
if(p->test==false)
{
cout<<"第"<<p->i<<"道题:"<<p->a<<p->op<<p->b<<"=";
cin>>p->ans;
if(p->ans==p->result)
{
cout<<"正确!"<<endl;
p->test=true;
}
else
{
cout<<"错误!"<<endl;
p->test=false;
count++;
}
}
p=p->next;
}
if(count==0)
{
cout<<"全部都答对了!"<<endl;
}
else
cout<<"还有"<< count<<"道没答对"<<endl;
baocun(head);
break;
case 3: exit(0);
}
}
void menu()
{
cout<<" 小学生练习题"<<endl;
cout<<"1. 开始练习"<<endl;
cout<<"2. 练习错题"<<endl;
cout<<"3. 退出程序"<<endl;
cout<<"选择执行的命令"<<endl;
}
int main()
{
while(1)
{
menu();
test();
}
return 0;
}
运行主界面为
可以随机产生十道题,做错的题目可以下次通过练习错题来继续做。