我试图随机生成一个方程,也有50%的机会是错误的,并显示不正确的答案。不正确的答案应该有一个错误-2、-1、+1或+2。
有时我的代码会打印这样的除法方程(我不能发布图像):2/10=13 1/5=43等等。
我搞不懂为什么这个等式显示的是一组没有一起检查的数字?
(它首先调用oncreateview方法中的generateEnumbers()
public void generateNumbers() {
//randomly generate 2 numbers and an operator
number1 = (int) (Math.random() * 10) + 1;
number2 = (int) (Math.random() * 10) + 1;
operator = (int) (Math.random() * 4) + 1;
//50% chance whether the displayed answer will be right or wrong
rightOrWrong = (int) (Math.random() * 2) + 1;
//calculate the offset of displayed answer for a wrong equation (Error)
error = (int) (Math.random() * 4) + 1;
generateEquation();
}
public void generateEquation() {
StringBuilder equation = new StringBuilder();
//append the first number
equation.append(number1);
//generate/append the operator and calculate the real answer
if (operator == 1) {
equation.append(" + ");
actualAnswer = number1 + number2;
} else if (operator == 2) {
equation.append(" - ");
actualAnswer = number1 - number2;
} else if (operator == 3) {
equation.append(" x ");
actualAnswer = number1 * number2;
} else if (operator == 4) {
if ((number1%number2==0) && (number1>number2)) {
actualAnswer = number1 / number2;
} else {
generateNumbers();
}
equation.append(" / ");
}
//append the second number and the equals sign
equation.append(number2 + " = ");
//we will display the correct answer for the equation
if (rightOrWrong == 1) {
displayedAnswer = actualAnswer;
equation.append(displayedAnswer);
}
//we will display an incorrect answer for the equation
//need to calculate error (-2, -1, +1, +2)
else {
if (error == 1) {
displayedAnswer = actualAnswer - 1;
} else if (error == 2) {
displayedAnswer = actualAnswer - 2;
}else if (error == 3) {
displayedAnswer = actualAnswer + 1;
}else {
displayedAnswer = actualAnswer + 2;
}
//append the displayed answer with error
equation.append(displayedAnswer);
}
questionNumber.setText("You have answered " + count + " out of 20 questions");
finalEquation.setText(equation.toString());
}
2条答案
按热度按时间xwmevbvl1#
我想你需要放一个
return
通话后的声明generateNumbers
在因为这将重启整个过程,而不是继续增加数字。
zysjyyx42#
更改代码以解决低概率除法问题: