一、设计思想:
1、定义变量;
2、生成随机数;
3、判断大小(为假分数做准备);
4、利用switch语句判定输出为整数运算还是假分数运算;
5、利用switch语句判定运算法则并输出(其中包含除数以及分母是否为0判断以及为0的解决办法)。
程序源代码:
#include<iostream> #include<ctime> #include<cstdlib> using namespace std; void main(){ int x,x0,y,y0,z,z0,i,n,m;//定义变量 srand(time(0));//定义时间种子 for(i=0;i<30;i++){//利用FOR循环进行多次输出 n=i+1; x = rand()%99+1;//产生随机数 x0 = rand()%99+1; y = rand()%99+1; y0 = rand()%99+1; z = rand()%(3-0+1)+0; z0 = rand()%(1-0+1)+0; cout<<n<<" "<<z0<<" ";//计数 if(x<x0){//保证x>x0 m=x; x=x0; x0=m; } if(y<y0){//保证y>y0 m=y; y=y0; y0=m; } switch(z0){//判断整数或分数 case 0:{ switch(z){//运算法则判断 case 0: cout<<x<<" + "<<y<<" ="<<endl; break; case 1: cout<<x<<" - "<<y<<" ="<<endl; break; case 2: cout<<x<<" * "<<y<<" ="<<endl; break; case 3: if(y!=0)//防止出现除数为零的情况 cout<<x<<" / "<<y<<" ="<<endl; else i--; break; } break; } case 1:{ if(x0!=0||y0!=0){ switch(z){//运算法则判断 case 0: cout<<"("<<x<<"/"<<x0<<")"<<" + "<<"("<<y<<"/"<<y0<<")"<<" ="<<endl; break; case 1: cout<<"("<<x<<"/"<<x0<<")"<<" - "<<"("<<y<<"/"<<y0<<")"<<" ="<<endl; break; case 2: cout<<"("<<x<<"/"<<x0<<")"<<" * "<<"("<<y<<"/"<<y0<<")"<<" ="<<endl; break; case 3: if(y!=0)//防止出现除数为零的情况 cout<<"("<<x<<"/"<<x0<<")"<<" / "<<"("<<y<<"/"<<y0<<")"<<" ="<<endl; else i--; break; } } else i--; break; } } } }
运行结果截图:
原因:只是简单的想了设计思想,其实实际操作比较繁琐!