【发布时间】:2015-07-07 05:52:55
【问题描述】:
我正在尝试随机生成一个方程,该方程也有 50% 的几率出错并显示错误的答案。错误答案的错误应该是 -2、-1、+1 或 +2。
有时我的代码会打印出这样的除法方程(我无法发布图像): 2 / 10 = 13 1 / 5 = 43 等等
我不明白为什么等式会显示未检查在一起的混合数字?
(它从在我的 onCreateView 方法中调用 generateNumbers() 开始
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());
}
【问题讨论】:
-
您的代码中有一些奇怪的东西。您生成数字,然后生成方程式。然后在生成方程时,如果它们不适合除法,则生成新数字,因此再次调用生成数字函数。这又再次调用生成方程函数,但当它完成时,第一次调用生成方程继续。
-
是的,当我试图解决它时,我就是这么想的,但是我太深入了,无法弄清楚。标记的答案解决了它
标签: java android random equation