Math.cos、sin 和 tan 在 Java 中返回不准确的值 [英] Math.cos, sin and tan returning inaccurate values in Java

查看:102
本文介绍了Math.cos、sin 和 tan 在 Java 中返回不准确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发带有 Java 图形用户界面的计算器.项目已完成,但三角函数无法正常工作.这是cos函数的方法:

I am working on a calculator with a GUI in Java. The project is done, however the trigonometric functions do not work properly. This is the method for the cos function:

public void actionPerformed(ActionEvent evt) {
input = Double.valueOf(Display.getText());
ans = Math.cos(Math.toRadians(input));
Display.setText(String.valueOf(ans));
} 

其中显示"是文本区域.问题是函数返回不准确的值.例如,当我输入 90 并单击 cos 按钮时,返回数字 6.123233995736766E-17.sin 和 tan 按钮也以类似的方式不准确(如有必要,我可以进一步解释).代码哪里出错了,怎么解决

Where "Display" is the text area. The problem is that the functions return inaccurate values. For example, when I enter 90 and click the cos button, the number 6.123233995736766E-17 is returned. The sin and tan buttons are also inaccurate in a similar manner (I can explain further if necessary). Where is the code going wrong, and how can I solve this

推荐答案

cos 返回的值并非不准确.当您输入 90 并使用 Math.toRadians 方法将其转换为弧度时,结果 完全是 pi/2,因此当您将此非精确值传递给 cos 它会给出一个非精确值.偷看这里听听传奇 :-)

The value returned by cos is not inaccurate. When you input 90, and convert it to radian using the method Math.toRadians, the result is not exactly pi/2, and hence when you pass this non-exact value to cos it gives a non-exact value. Peek here to hear from the legend :-)

至于你的情况,你需要对cos的结果进行四舍五入.看看这里

As for your situation, you need to round the result of cos. Take a look here

你可以这样做:

public void actionPerformed(ActionEvent evt) {
    input = Double.valueOf(Display.getText());
    ans = Math.cos(Math.toRadians(input));
    Display.setText(String.format("%.6f", ans));
} 

这篇关于Math.cos、sin 和 tan 在 Java 中返回不准确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆