Android: 除法和减法总是等于 1.0
Android: Division and subtraction always equal 1.0
我正在制作一个简单的计算器,但是当我尝试除法时总是得到 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));
}
请帮忙!
您正在读取 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.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));
}
请帮忙!
您正在读取 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));
}