如何正确舍入这个数字?

时间:2019-10-06 18:54:13

标签: java floating-point rounding

我应该得到PI和PI / 2的余弦和正弦,角度为0。除了PI / 2的余弦,我的所有数字都是正确的。

预期输出:

Radians: (cos, sin)
0.0: 1.0, 0.0
1.5707963267948966: 0.0, 1.0
3.141592653589793: -1.0, 0.0

我的输出:

Radians: (cos, sin)
0.0: 1.0, 0.0
1.5707963267948966: 1.0, 1.0
3.141592653589793: -1.0, 0.0

public class UnitCircle 
{
    public static void main(String[] args)
    {
        System.out.println("Radians: (cos, sin)");

        double angle = 0.0;
        double piDivideTwo = Math.PI/2.0;
        double pi = Math.PI;

        System.out.println(angle + ": " + Math.cos(angle) + ", " + Math.sin(angle) );


        double cosine = Math.cos(piDivideTwo); 
        cosine = Math.round(cosine * 100) / 100.0;

        System.out.println(piDivideTwo + ": " + Math.cos(cosine) + ", " + Math.sin(piDivideTwo) );

        double sin = Math.sin(pi);
        sin = Math.round(sin *100) / 100.0;

        System.out.println(pi + ": " + Math.cos(pi) + ", " + Math.sin(sin) );
    }
}

1 个答案:

答案 0 :(得分:1)

它似乎可以使用两次input { border: none; }cos的原因只是因为它的值是sin


您只需要计算一次0,然后使用格式打印,因为PI / 2和PI不可能是理想值

cos,sin
相关问题