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