Android:除法和减法始终等于1.0

时间:2016-02-04 03:13:49

标签: java android calculator arithmetic-expressions

我正在制作一个简单的计算器,但是当我尝试划分时,我总是得到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));
}

请帮忙!

1 个答案:

答案 0 :(得分: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));
}