2016-08-12 56 views
2

我是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))); 
+0

類型化分子或分母加倍會返回雙倍值 –

回答

2

(((double)a/(double)b))這會給你= 0.57,然後這(int)這將在這裏轉換0.57爲0 (int)(((double)a/(double)b));,因爲整數只能容納whole numbers因此十進制值將被截斷。

使用這種方式來保持十進制值

double correctAnswer = (((double)a/(double)b)); 

更新:爲了實現十進制結果,只有一個操作需要轉換爲雙和第二個參數的優化將編譯器來完成。

更新點數:@ stackoverflowuser2010和@ cricket_007。

double correctAnswer = (double)a/b; 

這也可以在不與explicit類型轉換類型轉換這是由編譯器完成鑄造完成。

例積分:@Andreas

double correctAnswer = a; // a , will automatically converted to double 
correctAnswer /= b; 
+1

您只需投一個值,兩者都不是必需的 –

+0

商定了@ cricket_007 –

+0

感謝大家的幫助。我相信我需要指定我正在投射的值的原始類型(int),因此(int)(((double)a /(double)b)); –

0

您需要刪除鑄師之前,INT:

這條線:

double correctAnswer = (int)(((double)a/(double)b)); 

應該是這樣的:

double correctAnswer = (((double)a/(double)b)); 
4

選擇之一:

double correctAnswer = (double)a/b; 

double correctAnswer = a/(double)b; 

double correctAnswer = (double)a/(double)b; 
+1

或者'1.0 * a/b' –

+1

或者不投射:'double correctAnswer = a; correctAnswer/= b;' – Andreas