Java随机产生50道100以内加减法输出,并编写测试代码
时间: 2024-05-15 13:15:02 浏览: 168
批量生成100以内的加法/减法算式基、批改练习并存储
5星 · 资源好评率100%
1. 随机产生50道100以内的加减法题目:
```java
import java.util.Random;
public class RandomMath {
public static void main(String[] args) {
Random random = new Random();
for (int i = 0; i < 50; i++) {
int num1 = random.nextInt(100);
int num2 = random.nextInt(100);
int operator = random.nextInt(2); // 0表示加法,1表示减法
if (operator == 0) {
System.out.println(num1 + " + " + num2 + " = ");
} else {
System.out.println(num1 + " - " + num2 + " = ");
}
}
}
}
```
2. 编写测试代码:
```java
public class RandomMathTest {
public static void main(String[] args) {
RandomMath randomMath = new RandomMath();
int correctCount = 0; // 正确答题数
int wrongCount = 0; // 错误答题数
for (int i = 0; i < 50; i++) {
int num1 = randomMath.generateRandomNumber();
int num2 = randomMath.generateRandomNumber();
int operator = randomMath.generateRandomOperator();
int answer = randomMath.calculateAnswer(num1, num2, operator);
System.out.print(num1 + (operator == 0 ? " + " : " - ") + num2 + " = ");
// 模拟用户输入答案
int userAnswer = randomMath.generateRandomAnswer(answer - 10, answer + 10);
System.out.print(userAnswer + " ");
// 判断答案是否正确
if (userAnswer == answer) {
System.out.println("√");
correctCount++;
} else {
System.out.println("× 正确答案为:" + answer);
wrongCount++;
}
}
System.out.println("测试结果:共答对" + correctCount + "题,答错" + wrongCount + "题");
}
}
```
其中,`RandomMath` 类包含了四个方法:
- `generateRandomNumber()`:随机生成 0-100 之间的整数
- `generateRandomOperator()`:随机生成 0 或 1,表示加法或减法
- `calculateAnswer(int num1, int num2, int operator)`:根据操作符计算答案
- `generateRandomAnswer(int min, int max)`:随机生成一个 min 到 max 之间的整数,用于模拟用户输入的答案。
阅读全文