Math.cos, sin and tan returning inaccurate values in Java

前端 未结 1 599
情书的邮戳
情书的邮戳 2021-01-26 00:06

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:

相关标签:
1条回答
  • 2021-01-26 00:32

    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 :-)

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

    You could do something like this:

    public void actionPerformed(ActionEvent evt) {
        input = Double.valueOf(Display.getText());
        ans = Math.cos(Math.toRadians(input));
        Display.setText(String.format("%.6f", ans));
    } 
    
    0 讨论(0)
提交回复
热议问题