我是Android新手,我在創建數學應用時遇到了問題。如何劃分兩個整數並返回Java中的雙精度
基本前提是向用戶顯示0到20之間的兩個數字(questionTextView),然後向用戶顯示包含3個不正確答案和1個正確答案的網格。用戶然後點擊正確的答案。
我遇到的問題是正確答案不顯示爲2個小數點。
E.g.問題:4/7
答1:12.59
答2:15.99
答3:9.93
回答4:0(應該是0.57)
我不理解爲什麼正確的答案不能正確顯示,因爲我已經將兩個整數都轉換爲雙精度幷包含十進制格式。
我試過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)));
類型化分子或分母加倍會返回雙倍值 –