随机产生四则运算
#include<iostream>
#define HOW 10
using namespace std;
char get_oper(int n)
{
switch(n)
{
case 0:return '+';
case 1:return '-';
case 2:return '*';
case 3:return '/';
}
}
int main()
{
int num1=0,num2=0,count=0;
float user_answer=0,right_answer=0;
int operators=0; //0:+ 1:- 2:* 3:/
for(int i=1;i<=HOW;i++)
{
//随机产生运算的数和运算符。
num1=rand();
num2=rand();
operators=rand()%4;
//为了避免除不尽的情况,使除法运算调整为都能整除的。
if(operators==3)num1=num2*(rand()%100);
//输出算式,等待用户输入结果。
cout<<i<<": "<<num1<<get_oper(operators)<<num2<<"=";
cin>>user_answer;
//自动计算出正确的答案,便于检查用户输入的对错
switch(operators)
{
case 0:right_answer=num1+num2;break;
case 1:right_answer=num1-num2;break;
case 2:right_answer=num1*num2;break;
case 3:right_answer=num1/num2;
}
//检查用户输入的答案
if(right_answer==user_answer)
{
cout<<"RIGHT"<<endl;
count++;
}
else
cout<<"WRONG"<<endl;
}
//输出统计的数据
cout<<"Right:"<<count<<" Wrong:"<<HOW-count<<" "<<count<<"/"<<HOW<<"="<<count/HOW;
return 0;
}