1 /*随即产生带有括号的30个式子
2 20133078_yulei*/
3 #include <iostream>
4 #include <string>
5 #include <time.h>//用到了time函数
6 #define random(x)(rand()%x)
7 #define N 30 //预定产生30个
8 using namespace std;
9 void sort(int a[], int n)
10 {
11 int i,j,temp;
12 for (j=0;j<n-1;j++)
13 for (i=0;i<n-1-j;i++)
14 if(a[i]>a[i+1])
15 {
16 temp=a[i];
17 a[i]=a[i+1];
18 a[i+1]=temp;
19 }
20 }
21
22 void L(int &w)
23 {
24 int q=rand()%100;
25 if(q%2==0)
26 {
27 cout<<"(";
28 w++;
29 }
30
31 }
32 void R(int &w)
33 {
34 int q=rand()%100;
35 if(q%7==0)
36 {
37 cout<<")";
38 w--;
39 }
40 }
41
42 void main()
43 {
44 srand((unsigned) time(NULL)); //用时间做种,每次产生随机数不一样
45 int rand1[N][10]; //30个式子,每列最多10个数
46 int i=0,j=0,k=0,w=0;
47 string ch[N][10]={}; //运算符数组,最多允许10个
48 int num[N]; //每行式子的运算符的个数
49 int cc,ff,kk;
50 cout<<"***输入有无乘除法:(0无/1有):";
51 cin>>cc;
52 cout<<"***输入有无负数:(0无/1有):";
53 cin>>ff;
54 cout<<"***输入有无括号:(0无/1有):";
55 cin>>kk;
56 for(i=0;i<N;i++) //每行参与运算的个数,不能为零
57 {
58 num[i]=rand()%9+1;
59 if(num[i]==0)
60 i--;
61 }
62 for(i=0;i<N;i++)
63 {
64 switch(cc)
65 {
66 case 0:{
67 for (j=0;j<num[i];j++) //参与运算的运算符
68 {
69 int k=rand()%2;
70 switch(k%2)
71 {
72 case 0:ch[i][j]="+";break;
73 case 1:ch[i][j]="-";break;
74 }
75 }
76 }break;
77 case 1:
78 {
79 for (j=0;j<num[i];j++) //参与运算的运算符
80 {
81 int k=rand()%4;
82 switch(k%4)
83 {
84 case 0:ch[i][j]="+";break;
85 case 1:ch[i][j]="-";break;
86 case 2:ch[i][j]="*";break;
87 case 3:ch[i][j]="÷";
88 }
89 }
90 }
91 }
92
93 }
94
95 switch(ff)
96 {
97 case 0:
98 {
99 for(i=0;i<N;i++) //产生参与运算的数
100 {
101 for (j=0;j<num[i]+1;j++)
102 {
103 rand1[i][j]=rand()%100; //参与运算的数据比运算符多1个
104 if(j!=0&&ch[i][j-1]=="/"&&rand1[i][j]==0) //除第一个数据外的其他数据前边是除法,则这个数不能为零
105 j=j-1; //回溯重新产生
106 }
107 }break;
108 }
109 case 1:
110 {
111 for(i=0;i<N;i++) //产生参与运算的数
112 {
113 for (j=0;j<num[i]+1;j++)
114 {
115 rand1[i][j]=rand()%139-39; //参与运算的数据比运算符多1个
116 if(j!=0&&ch[i][j-1]=="/"&&rand1[i][j]==0) //除第一个数据外的其他数据前边是除法,则这个数不能为零
117 j=j-1; //回溯重新产生
118 }
119 }break;
120 }
121 }
122
123 //数据有了,运算有了,剩下的就是将他们进行组合。
124 switch(kk)
125 {
126 case 1:
127 {
128 for(i=0;i<N;i++)
129 {
130 cout<<i+1<<".";
131 int k=0;
132 for (j=0;j<num[i]+1;j++)
133 {
134 int p;
135 L(k);
136 if (k>0)
137 p=j;
138 if(rand1[i][j]<0)
139 cout<<"("<<rand1[i][j]<<")";
140 else
141 cout<<rand1[i][j];
142 if(k>0&&p!=j)
143 R(k);
144 cout<<ch[i][j];
145 }
146 for(k;k!=0;)
147 {
148 R(k);
149 }
150 cout<<"= "<<endl;
151
152 }break;
153 }
154 case 0:
155 {
156 for(i=0;i<N;i++)
157 {
158 cout<<i+1<<".";
159 int k=0;
160 for (j=0;j<num[i]+1;j++)
161 {
162 if(rand1[i][j]<0)
163 cout<<"("<<rand1[i][j]<<")";
164 else
165 cout<<rand1[i][j];
166 cout<<ch[i][j];
167 }
168 cout<<"= "<<endl;
169
170 }
171 }
172 }
173
174
175 }