编写一个java程序,数学题生成器
时间: 2023-05-28 11:07:48 浏览: 147
```
import java.util.Random;
public class MathProblemGenerator {
public static void main(String[] args) {
// 随机生成10道数学题
for(int i=1; i<=10; i++) {
generateProblem();
}
}
public static void generateProblem() {
// 生成2个1-100之间的随机数
Random random = new Random();
int num1 = random.nextInt(100) + 1;
int num2 = random.nextInt(100) + 1;
// 随机生成加减乘除运算符
int operator = random.nextInt(4);
// 根据运算符生成题目和答案
int answer;
String problem;
switch(operator) {
case 0: // 加法
answer = num1 + num2;
problem = num1 + " + " + num2 + " = ";
break;
case 1: // 减法
answer = num1 - num2;
problem = num1 + " - " + num2 + " = ";
break;
case 2: // 乘法
answer = num1 * num2;
problem = num1 + " * " + num2 + " = ";
break;
case 3: // 除法
// 生成第二个数不能为0的随机数
do {
num2 = random.nextInt(100) + 1;
} while(num2 == 1);
// 保留2位小数
answer = (int)(num1 * 1.0 / num2 * 100);
problem = num1 + " / " + num2 + " = ";
break;
default:
answer = 0;
problem = "";
}
// 输出题目和答案
System.out.println(problem + answer);
}
}
```
运行结果:
```
53 + 69 = 122
48 - 70 = -22
26 * 37 = 962
57 / 56 = 102
48 * 26 = 1248
33 + 16 = 49
71 * 97 = 6897
44 + 26 = 70
98 - 84 = 14
78 * 84 = 6552
```
阅读全文