2016-02-04 40 views
-6

我正在做一個簡單的計算器,但是當我嘗試劃分時,我總是得到1.0,當我減去時我總是得到零。加法和乘法工作正常。Android:劃分和減法總是等於1.0

我讀過類似的問題,如: Why does integer division code give the wrong answer? Dividing two integers in Java gives me 0 or 100? Division in Java always results in zero (0)?

還有更多...

這裏是我的代碼的一部分:

if (minu) { 
    number1 = Double.valueOf(display1.getText().toString()); 
    number2 = Double.valueOf(display1.getText().toString()); 

    display1.setText(""); 
    display2.setText(""); 
    displaySymbol.setText(""); 

    answer = number1 - number2; 

    display1.setText(Double.toString(answer)); 
} 

和分部:

if (divid) { 
    number1 = Double.valueOf(display1.getText().toString()); 
    number2 = Double.valueOf(display1.getText().toString()); 

    display1.setText(""); 
    display2.setText(""); 
    displaySymbol.setText(""); 

    answer = number2/number1; 

    display1.setText(Double.toString(answer)); 
} 

請幫忙!

回答

6

您正在閱讀從display1兩次的價值,你忘了的number2閱讀改變display2


替換:

number2 = Double.valueOf(display1.getText().toString()); 

number2 = Double.valueOf(display2.getText().toString()); 

你的功能將結束是:

if(minu){ 
    number1 = Double.valueOf(display1.getText().toString()); 
    number2 = Double.valueOf(display2.getText().toString()); 

    display1.setText(""); 
    display2.setText(""); 
    displaySymbol.setText(""); 

    answer = number1 - number2; 

    display1.setText(Double.toString(answer)); 
} 
+1

哇,我是個白癡...謝謝您。 – Eklassen