【发布时间】:2015-06-18 19:26:29
【问题描述】:
所以这里的输出“H”给了我一个太长的数字,小数点在错误的位置,但否则整数是正确的。示例:
333433.33333 是显示的内容
应该显示333.43
我怀疑罪魁祸首是
`h = (double) Math.round(h * 100000) / 100000;`
但是当我将其更改为 h = (double) Math.round(h * 1000) / 1000; 时,它似乎没有帮助。
public class DoFCalculator extends Fragment {
EditText txtF;
Spinner aSpinner, cSpinner;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.calculators_fragment_dof, container, false);
Button button = (Button) rootView.findViewById(R.id.btn_Cal);
aSpinner = (Spinner) rootView.findViewById(R.id.aSpinner);
txtF = (EditText) rootView.findViewById(R.id.focal_length);
cSpinner = (Spinner) rootView.findViewById(R.id.coc);
final TextView txtAnswer = (TextView) rootView.findViewById(R.id.txt_H);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String F = txtF.getText().toString();
String A = aSpinner.getSelectedItem().toString();
String C = cSpinner.getSelectedItem().toString();
if (!F.isEmpty() ) {
txtAnswer.setText("H = " + Calcullate_H(F, A, C) + "");
} else {
Toast.makeText(getActivity(), "All data Required", Toast.LENGTH_LONG).show();
}
}
});
return rootView;
}
private double Calcullate_H(String txtF, String txtA, String txtC) {
double f = Double.parseDouble(txtF.toString());
double A = Double.parseDouble(txtA.toString());
double C = Double.parseDouble(txtC.toString());
double h = ((f * f) / (A * C)) + f;
h = (double) Math.round(h * 100000) / 100000;
return h;
}
}
【问题讨论】:
-
等式中的 h 是什么?
-
更改为
h = (double) (Math.round((h * 100000) / 100000)); -
这不是一个最小的例子。把它缩小,检查
h,我敢打赌你会发现你有一个简单的错字。 -
如果您想避免舍入问题(在以 2 为底的系统上进行以 10 为底的计算时不可避免),请使用 BigDecimal 而不是原语。
标签: java android math calculator