Fou*_*ast 1 java double android
我正在制作一个Android计算器,当我除以零时,我得到9.223372E + 18.为什么不显示NaN或崩溃?我认为它导致9.223372E + 18,因为这是最大可能的双值,因为我除以零并使用双数据类型.由于它会让用户感到困惑,我该如何解决这个问题呢?
大家好,感谢您的所有回复.我很感激.我在下面发布了我的代码.
public class CFM extends ActionBarActivity {
Double cfm, ac, volume;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cfm);
EditText e1 = (EditText) findViewById(R.id.editText1);
EditText e2 = (EditText) findViewById(R.id.editText2);
TextView t1 = (TextView) findViewById(R.id.editText3);
t1.setEnabled(false);
t1.setFocusable(false);
e1.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
EditText e1 = (EditText)findViewById(R.id.editText1);
EditText e2 = (EditText)findViewById(R.id.editText2);
volume = Double.parseDouble(e1.getText().toString());
cfm = Double.parseDouble(e2.getText().toString());
TextView t1 = (TextView) findViewById(R.id.editText3);
ac = cfm * 60 / volume;
t1.setText(Double.toString((double) Math.round(ac * 100) / 100));
}
});
e2.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
EditText e1 = (EditText)findViewById(R.id.editText1);
EditText e2 = (EditText)findViewById(R.id.editText2);
volume = Double.parseDouble(e1.getText().toString());
cfm = Double.parseDouble(e2.getText().toString());
TextView t1 = (TextView) findViewById(R.id.editText3);
ac = cfm * 60 / volume;
t1.setText(Double.toString((double) Math.round(ac * 100) / 100));
}
});
}
Run Code Online (Sandbox Code Playgroud)
9223372036854775807(粗略地9.223372E+18)是最大的可能long值.我可以看到这个除以零的唯一方法是你有一个类型的变量long.例如,以下代码打印9223372036854775807.
long a = 1;
a /= 0.0;
System.out.println(a);
Run Code Online (Sandbox Code Playgroud)
将a long除以a时double,将long转换为double第一个,结果为a double.任何正数double除以0.0给出Double.POSITIVE_INFINITY,1/0.0也是Double.POSITIVE_INFINITY.由于a具有类型long,因此将其转换回a long,从而提供尽可能大的long值.
但是,我们需要查看您的代码以了解为什么您有类型的变量long.
编辑
看过你的代码后,我现在意识到问题不是类型的变量,long而是你的使用Math.round.这定义如下:
返回与参数最接近的长度,并将关系向上舍入.
Math.round因此四舍五入Double.PositiveInfinity到9223372036854775807.将结果显示为2位小数的更好方法是这样的.
String result = Double.isInfinite(ac) || Double.isNaN(ac) ? "Error"
: new BigDecimal(ac).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
t1.setText(result);
Run Code Online (Sandbox Code Playgroud)
"Error"如果用户试图除以零,则会打印.
| 归档时间: |
|
| 查看次数: |
373 次 |
| 最近记录: |