public void onButtonClick(View v) {
int n1, n2, n3;
double calc;
EditText e1 = (EditText)findViewById(R.id.first_grade);
EditText e2 = (EditText)findViewById(R.id.second_grade);
EditText e3 = (EditText)findViewById(R.id.third_grade);
TextView t1 = (TextView)findViewById(R.id.calculate);
n1 = Integer.parseInt(e1.getText().toString());
n2 = Integer.parseInt(e2.getText().toString());
n3 = Integer.parseInt(e3.getText().toString());
calc = (n1 + n2 + n3)/3;
t1.setText(String.format("%.2f", calc));
}
这是我的代码,我也尝试过DecimalFormat,但是stackoverflow的所有解决方案都不适合我。
如果我分别输入11、22、10作为输入,我应该得到14.333333的结果,但结果是14.00。
有人知道如何解决此错误吗?或对此有解决方案?
自变量n1
,n2
和n3
是ints
,它们的和以及随后的分裂是整为好。这样,结果将被截断为整数。
为了获得准确的结果,您应该强制除法为浮点数。为此,操作数之一应为双精度。您可以通过替换3
为3.0
(n1 + n2 + n3) / 3.0
接下来,如何将结果四舍五入到两位小数。我们可以将结果乘以100,执行整数除法,然后再除以100并转换为double。
((n1 + n2 + n3) * 100 / 3) / 100.0
您可以查看解决此问题的其他方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句