程序生成30道四则运算(包括整数和真分数)

题目:

花二十分钟写一个能自动生成小学四则运算题目的命令行 “软件”, 分别满足下面的各种需求。下面这些需求都可以用命令行参数的形式来指定:

 除了整数以外,还要支持真分数的四则运算。 (例如:  1/6 + 1/8 = 7/24)

 

在软件工程课上,对于这道题目看了之后发现还是很简单的主要注意:

(1)使用随机函数生成运算数

(2)运算符号的随机确定

(3)考虑除数是否为0若为0将如何处理

(4)真分数的生成方法

思考之后我写了如下代码:

 1 #include<iostream>
 2 using namespace std;
 3 #include<time.h>
 4 #include<string>
 5 
 6 int main()
 7 {
 8     int count=0 ;
 9     srand(time(NULL));//用系统当前时间设置rand()随机序列种子,保证每次运行随机序列不一样 
10     char ch;
11     while(count<30)
12     {
13         cout<<"选择做整数运算(输入'a')或真分数运算(输入'b')"<<endl;
14         //产生整数的运算
15         cin>>ch;
16         if(ch=='a')
17         {cout<<"开始产生四则运算:"<<endl;
18         int shu1=0,shu2=0;
19     //随机数产生0-100
20     //shu1=srand(1000);
21 
22     
23     shu1=0+rand()%100;
24     shu2=0+rand()%100;
25 
26     int sum=0;
27     int fushu=0;
28     string fuhao[4]={"+","-","*","/"};
29     fushu=((0+rand()%4)+4)%4;
30     //cout<<fushu<<endl;
31 
32     //判断shu2是否为0和是否为除法 若为则重新生成
33     while(shu2==0&fushu==3)
34     {
35         shu2=0+rand()%100;
36     }
37     //随机产生的符号
38     switch(fushu)
39     {
40     case 0:cout<<shu1<<fuhao[fushu]<<shu2<<endl;break;
41     case 1:cout<<shu1<<fuhao[fushu]<<shu2<<endl;break;
42     case 2:cout<<shu1<<fuhao[fushu]<<shu2<<endl;break;
43     case 3:cout<<shu1<<fuhao[fushu]<<shu2<<endl;break;
44     }
45         }
46 
47     //产生真分数的运算
48         if(ch=='b')
49         {
50     int zhenfens1_m=0,zhenfens1_z=0,zhenfens2_m=0,zhenfens2_z=0;
51     
52     zhenfens1_m=0+rand()%100;
53     zhenfens1_z=0+rand()%100;
54 
55     //判断产生的真分数正确性
56     while(zhenfens1_m<zhenfens1_z)
57     {
58         zhenfens1_m=0+rand()%100;
59         zhenfens1_z=0+rand()%100;
60     }
61 
62     zhenfens2_m=0+rand()%100;
63     zhenfens2_z=0+rand()%100;
64 
65     //判断产生的真分数正确性
66     while(zhenfens2_m<zhenfens2_z)
67     {
68         zhenfens2_m=0+rand()%100;
69         zhenfens2_z=0+rand()%100;
70     }
71 
72     string fuhao[4]={"+","-","*","/"};
73     int fushu=((0+rand()%4)+4)%4;
74     //cout<<fushu<<endl;
75 
76     //判断shu2是否为0和是否为除法 若为则重新生成
77     //随机产生的符号
78     switch(fushu)
79     {
80     case 0:cout<<"("<<zhenfens1_z<<"/"<<zhenfens1_m<<")"<<fuhao[fushu]<<"("<<zhenfens2_z<<"/"<<zhenfens2_m<<")"<<endl;break;
81     case 1:cout<<"("<<zhenfens1_z<<"/"<<zhenfens1_m<<")"<<fuhao[fushu]<<"("<<zhenfens2_z<<"/"<<zhenfens2_m<<")"<<endl;break;
82     case 2:cout<<"("<<zhenfens1_z<<"/"<<zhenfens1_m<<")"<<fuhao[fushu]<<"("<<zhenfens2_z<<"/"<<zhenfens2_m<<")"<<endl;break;
83     case 3:cout<<"("<<zhenfens1_z<<"/"<<zhenfens1_m<<")"<<fuhao[fushu]<<"("<<zhenfens2_z<<"/"<<zhenfens2_m<<")"<<endl;break;
84     }
85 
86         }
87     count++;
88     }
89 }

但是我写的程序没有类的封装还有也不好扩展,所以还有很大缺陷,若有朋友看了我的代码可以给我一下建议。

原文地址:https://www.cnblogs.com/ly199553/p/5247658.html