<分区>
我是 Android 的新手,我在使用我正在创建的数学应用程序时遇到了问题。
基本前提是向用户显示 0 到 20 之间的 2 个数字 (questionTextView),然后向用户显示包含 3 个错误答案和 1 个正确答案的网格。然后用户点击正确答案。
我遇到的问题是正确答案没有显示到小数点后两位。
例如问题:4/7
答案 1:12.59
答案 2:15.99
答案 3:9.93
答案4:0(应该是0.57)
我不明白为什么正确答案没有正确显示,因为我已将两个整数转换为 double 并包含十进制格式。
我试过 Math.round(),但我无法让它工作 - 可能是因为我在 for 循环中生成问题的方式????
正确显示错误的答案。
如有任何帮助,我们将不胜感激。
这是我的代码:
private static DecimalFormat df2 = new DecimalFormat("#.##");
public void generateQuestion(){
//Create 2 random numbers between 0 and 20.
Random rand = new Random();
int a = rand.nextInt(21);
int b = rand.nextInt(21);
if (a==b){
b = rand.nextInt(21);
}
questionTextView.setText(Integer.toString(a) + " / " + Integer.toString(b));
/*Create a random number between 0 and 3 to determine the grid square of
the correct answer */
locationOfCorrectAnswer = rand.nextInt(4);
//Calculate the correct answer.
double correctAnswer = (int)(((double)a/(double)b));
//Generate an incorrect answer in case the correct answer is
randomly generated.
double inCorrectAnswer;
/*Loop through each square and assign either the correct answer or
a randomly generated number. */
for (int i=0; i<4; i++){
if (i == locationOfCorrectAnswer){
answers.add(df2.format(correctAnswer).toString());
} else {
inCorrectAnswer = 0.05 + rand.nextDouble() *20.0;
while (inCorrectAnswer == correctAnswer){
inCorrectAnswer = 0.05 + rand.nextDouble() *20.0;
}
answers.add(df2.format(inCorrectAnswer).toString());
}
}
//Assign an answer to each of the buttons.
button0.setText((answers.get(0)));
button1.setText((answers.get(1)));
button2.setText((answers.get(2)));
button3.setText((answers.get(3)));