随机生成30道整数或者真分数组成的两位数的四则运算
编程实现随机生成30道随机整数或者真分数组合的两位数四则运算的计算题
将题目分解后的思路:
1.首先通过系统时间初始化随机数种子然后生成两个随机整数和两个随机真分数来组合进行四则运算。
2.再生成两个随机数用于除四取余进行四则运算整数和真分数组合和四种运算符号选择。
3.利用switch-case语句进行选择,外部switch-case语句进行整数和真分数四种情况组合,每种组合内部嵌套一个switch-case语句进行四则运算四种运算符号的选择并输出结果,再利用for语句完成30次循环。
问题:
根据老师查出的问题进行改正,可输出真分数形式,去除多余的代码
程序源代码:
//20133059 武于微 信1301-1班 #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; } } }