You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
my_project/src/JuniorQuestionGenerator.java

55 lines
1.7 KiB

import java.util.Random;
/**
* 初中题目生成器实现
* 生成适合初中生的数学题目,包含平方和开根号运算
*/
public class JuniorQuestionGenerator implements QuestionGenerator {
@Override
public String generateQuestion(StringBuilder question, Random random) {
// 随机生成1-5个操作数
int operandCount = random.nextInt(5) + 1;
String[] operators = {"+", "-", "*"};
String[] chosenOperators = new String[operandCount - 1];
// 确定包含平方或开根号的操作数位置
int specialPosition = random.nextInt(operandCount);
// 生成所有操作数
for (int i = 0; i < operandCount; i++) {
if (i == specialPosition) {
// 特殊操作数:平方或开根号
boolean isSquare = random.nextBoolean();
int num = random.nextInt(100) + 1;
if (isSquare) {
// 生成平方题
question.append(num).append("^2");
} else {
// 生成开根号题,确保是完全平方数
int sqrtNum = random.nextInt(10) + 1;
num = sqrtNum * sqrtNum;
question.append("√").append(num);
}
} else {
// 普通操作数
int num = random.nextInt(100) + 1;
question.append(num);
}
// 添加运算符(除了最后一个操作数)
if (i < operandCount - 1) {
chosenOperators[i] = operators[random.nextInt(operators.length)];
question.append(" " + chosenOperators[i] + " ");
}
}
// 10%的概率添加外层括号(如果有多个操作数)
if (operandCount > 1 && random.nextDouble() < 0.1) {
question.insert(0, "(").append(")");
}
question.append(" = ?");
return question.toString();
}
}