我正在开发一个可以计算三角函数的安卓计算器应用程序。我发现我的计算器显示:
Cos 90° = 6.123233995736766E-17 instead of Cos 90° = 0
Cos 270° = -1.8369701987210297E-16 instead of Cos 270° = 0
Tan 180° = -1.2246467991473532E-16 instead of Tan 180° = 0
Tan 360° = -2.4492935982947064E-16 instead of Tan 360° = 0
我知道这些值实际上意味着 0
但这些计算可能会让用户感到有些困惑。我还测试了 0°、15°、18°、22.5°、30°、36°、45°、60° 和 72° 的 Cos 和 Tan 值。他们似乎工作正常。我正在使用 Eclipse 制作这个应用程序。
我的问题是“如何让我的计算器显示用户友好的 Cos 和 Tan 函数值?”。
这是我的 Cos 和 Tan 函数代码:
ImageButton btnCos;
ImageButton btnTan;
TextView txtDisplay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCos = (ImageButton) findViewById(R.id.btnCos);
btnTan = (ImageButton) findViewById(R.id.btnTan);
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
btnCos.setOnClickListener(this);
btnTan.setOnClickListener(this);
}
Double total = 0.0;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.btnCos) {
if (txtDisplay.getText().equals("")) {
txtDisplay.setText("");
}
else {
total = Math.cos(Math.toRadians(Double.parseDouble(txtDisplay.getText().toString())));
txtDisplay.setText("");
txtDisplay.setText(txtDisplay.getText().toString() + total);
}
}
else if (v.getId() == R.id.btnTan) {
if (txtDisplay.getText().equals("")) {
txtDisplay.setText("");
}
else {
total = Math.tan(Math.toRadians(Double.parseDouble(txtDisplay.getText().toString())));
txtDisplay.setText("");
txtDisplay.setText(txtDisplay.getText().toString() + total);
}
}
最佳答案
Java 数学三角函数使用弧度。有一个效用函数,Math.toRadians(degrees)
(你可能需要 round()
- 所以我相信你想要这样的东西,
System.out.println(Math.round(Math.cos(Math.toRadians(90))));
输出是
0
关于java - 如何获得 Cos 和 Tan 函数的用户友好值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25367430/