1. 程式人生 > >自動生成300道四則運算題

自動生成300道四則運算題

static dom 自動 string bre mat rate generated pri

1 public class questions {
2
3 public static void main(String[] args) {
4 // TODO Auto-generated method stub
5 int a=(int)(Math.random()*100);
6 int b=(int)(Math.random()*100);
7 int c=(int)(Math.random()*100);
8
9 for(int i=0;i<300;i++){
10 String q="";
11 int ans=0;
12 int[] flag=new int[2];
13 for(int j=0;j<2;j++){
14 int f=(int)(Math.random()*4);
15 switch(f){
16 case 0:
17 if(j==0){
18 q=a+"+"+b;
19 }
20 else{
21 q=q+"+"+c;
22 }
23 flag[j]=0;
24 break;
25 case 1:
26 if(j==0){
27 q=a+"-"+b;
28 }
29 else{
30 q=q+"-"+c;
31 }
32 flag[j]=1;
33 break;
34 case 2:
35 if(j==0){
36 q=a+"*"+b;
37 }
38 else{
39 q=q+"*"+c;
40 }
41 flag[j]=2;
42 break;
43 case 3:
44 if(j==0){
45 q=a+"/"+b;
46 }
47 else{
48 q=q+"/"+c;
49 }
50 flag[j]=3;
51 break;
52 }
53 }
54 if(flag[0]<2){
55 if(flag[1]<2){
56 if(flag[0]==0){
57 ans=a+b;
58 }
59 else{
60 ans=a-b;
61 }
62 if(flag[1]==0){
63 ans+=c;
64 }
65 else{
66 ans-=c;
67 }
68 }
69 else{
70 if(flag[1]==2){
71 ans=b*c;
72 }
73 else{
74 if(c==0){
75 System.out.println("分母為零,此題無解");
76 continue;
77 }
78 ans=b/c;
79 }
80 if(flag[0]==0){
81 ans+=a;
82 }
83 else{
84 ans=a-ans;
85 }
86 }
87 }
88 else{
89 if(flag[0]==2){
90 ans=a*b;
91 }
92 else{
93 if(b==0){
94 System.out.println("分母為零,此題無解");
95 continue;
96 }
97 ans=a/b;
98 }
99 if(flag[1]==0){
100 ans+=c;
101 }
102 else if(flag[1]==1){
103 ans-=c;
104 }
105 else if(flag[1]==2){
106 ans*=c;
107 }
108 else{
109 if(c==0){
110 System.out.println("分母為零,此題無解");
111 continue;
112 }
113 ans/=c;
114 }
115 }
116
117 System.out.println(q);
118 System.out.println("答案是:"+ans);
119 }
120 }
121
122 }

自動生成300道四則運算題