有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

计算sin-cos和tan时缺乏精度(java)

当我运行这段代码时

System.out.println( Math.cos(8.8485279795) ); // should be : 0.988098452127
System.out.println( Math.sin(23.437101628) ); // should be :0.397742095267
System.out.println( Math.tan(52.2166666666667) ); // should be : 1.289966871548
System.out.println( Math.cos(23.437101628) ); // should be :0.917497261932
System.out.println( Math.sin(8.8485279795) ); //should be : 0.153822784089

输出是这样的

-0.8385118249144639
-0.9922171619691422
-2.500855651260892
-0.12451949041776937
0.5448833998926885

我怎样才能解决这个问题


共 (1) 个答案

  1. # 1 楼答案

    这并不是缺少精度,而是因为你正在将度传递给需要弧度的函数。使用^{}修复。像

    System.out.println(Math.cos(Math.toRadians(8.8485279795)));
    System.out.println(Math.sin(Math.toRadians(23.437101628)));
    System.out.println(Math.tan(Math.toRadians(52.2166666666667)));
    System.out.println(Math.cos(Math.toRadians(23.437101628)));
    System.out.println(Math.sin(Math.toRadians(8.8485279795)));
    

    我得到了(如你所料)

    0.9880984521266581
    0.39774209526711635
    1.2899668715484742
    0.9174972619318948
    0.1538227840890365