C语言实现四则运算

时间:2022-10-25 20:40:19

学生:宋丹丹 张潇裕

#include<iostream>
#include<ctime>
using namespace std;
void main()
{
int x1,x2,a,b,i,x3,x4,x5,x6;
srand(time(0)); //通过系统时间初始化随机数种子,若不设置则每次产生随机数相同
for(i=1;i<=30;i++)
{
x1=rand()%100; //产生随机整数
x2=rand()%100;
x3=rand()%100;
x4=rand()%100;
x5=rand()%100;
x6=rand()%100;
for(;x4==0;) //用于分母是否为零的判断
{
x4=rand()%100;
}
for(;x6==0;) //用于分母是否为零的判断
{
x6=rand()%100;
}
a=rand()%4; //产生随机整数用于除四取余后进行四种运算符号和四种数的选择
b=rand()%4;
switch(b) //用于随机整数和真分数四种组合情况的选择
{
case 0: //整数整数运算
switch(a) //用于四则运算四种符号的选择
{
case 0:
cout<<x1<<"+"<<x2<<"="<<endl;
break;
case 1:
cout<<x1<<"-"<<x2<<"="<<endl;
break;
case 2:
cout<<x1<<"*"<<x2<<"="<<endl;
break;
case 3:
for(;x2==0;) //用于分母是否为零的判断
{
x2=rand()%100;
}
cout<<x1<<"/"<<x2<<"="<<endl;
break;
default:
break;
}
break;
case 1: //分数分数运算
for(;x3>x4;)
{
x3=rand()%100;
}
for(;x5>x6;)
{
x5=rand()%100;
}
switch(a)
{
case 0:
cout<<"("<<x3<<"/"<<x4<<")"<<"+"<<"("<<x5<<"/"<<x6<<")"<<"="<<endl;
break;
case 1:
cout<<"("<<x3<<"/"<<x4<<")"<<"-"<<"("<<x5<<"/"<<x6<<")"<<"="<<endl;
break;
case 2:
cout<<"("<<x3<<"/"<<x4<<")"<<"*"<<"("<<x5<<"/"<<x6<<")"<<"="<<endl;
break;
case 3:
for(;x5==0;)
{
x5=rand()%100;
}
for(;x5>x6||x5==x6;)
{
x5=rand()%100;
}
cout<<"("<<x3<<"/"<<x4<<")"<<"/"<<"("<<x5<<"/"<<x6<<")"<<"="<<endl;
break;
default:
break;
}
break;
case 2: //整数分数运算
for(;x3>x4;)
{
x3=rand()%100;
}
switch(a)
{
case 0:
cout<<x1<<"+"<<"("<<x3<<"/"<<x4<<")"<<"="<<endl;
break;
case 1:
cout<<x1<<"-"<<"("<<x3<<"/"<<x4<<")"<<"="<<endl;
break;
case 2:
cout<<x1<<"*"<<"("<<x3<<"/"<<x4<<")"<<"="<<endl;
break;
case 3:
for(;x3==0;)
{
x3=rand()%100;
}
for(;x3>x4||x3==x4;)
{
x3=rand()%100;
}
cout<<x1<<"/"<<"("<<x3<<"/"<<x4<<")"<<"="<<endl;
break;
default:
break;
}
break;
case 3: //分数整数运算
for(;x5>x6;)
{
x5=rand()%100;
}
switch(a)
{
case 0:
cout<<"("<<x5<<"/"<<x6<<")"<<"+"<<x2<<"="<<endl;
break;
case 1:
cout<<"("<<x5<<"/"<<x6<<")"<<"-"<<x2<<"="<<endl;
break;
case 2:
cout<<"("<<x5<<"/"<<x6<<")"<<"*"<<x2<<"="<<endl;
break;
case 3:
for(;x2==0;) //用于分母是否为零的判断
{
x2=rand()%100;
}
cout<<"("<<x5<<"/"<<x6<<")"<<"/"<<x2<<"="<<endl;
break;
default:
break;
}
break;
default:
break;
}
}
}