java.用1~100范围内随机数出20道两个数进行加减乘除运算的练习题,输出这些题目
时间: 2024-05-09 13:20:36 浏览: 102
Java实现随机出题,10道10以内加减法计算代码实例
以下是Java代码实现:
```java
import java.util.Random;
public class MathExercise {
public static void main(String[] args) {
Random random = new Random(); // 创建随机数生成器对象
for (int i = 0; i < 20; i++) { // 循环生成20道题目
int num1 = random.nextInt(100) + 1; // 生成1~100范围内的随机数
int num2 = random.nextInt(100) + 1; // 生成1~100范围内的随机数
int operator = random.nextInt(4); // 生成0~3范围内的随机数,分别代表加减乘除四种运算
// 根据运算符号计算答案
int answer = 0;
String operatorStr = "";
switch (operator) {
case 0: // 加法
answer = num1 + num2;
operatorStr = "+";
break;
case 1: // 减法
answer = num1 - num2;
operatorStr = "-";
break;
case 2: // 乘法
answer = num1 * num2;
operatorStr = "×";
break;
case 3: // 除法
if (num2 == 0) { // 避免除数为0
num2 = 1;
}
answer = num1 / num2;
operatorStr = "÷";
break;
}
// 输出题目和答案
System.out.println((i + 1) + ". " + num1 + " " + operatorStr + " " + num2 + " = " + answer);
}
}
}
```
运行结果:
```
1. 30 + 14 = 44
2. 35 × 34 = 1190
3. 81 ÷ 98 = 0
4. 5 - 18 = -13
5. 60 + 1 = 61
6. 81 + 73 = 154
7. 92 - 37 = 55
8. 26 + 55 = 81
9. 49 - 15 = 34
10. 92 × 47 = 4324
11. 71 + 7 = 78
12. 7 × 43 = 301
13. 90 - 34 = 56
14. 51 + 49 = 100
15. 78 ÷ 20 = 3
16. 58 ÷ 66 = 0
17. 21 + 75 = 96
18. 86 - 54 = 32
19. 43 - 23 = 20
20. 23 ÷ 23 = 1
```
阅读全文