回 帖 发 新 帖 刷新版面

主题:[讨论]请大家帮忙看一个小问题

//下面是java Math类的一个小练习,为什么不进行乘除100的操作,得到的结果就不正确呢?请求大家指点一下,谢谢!
//right,这个结果正确
public class SinCosTan {
  public static void main(String[] args) {
    double sin30,cos60,tan45;
    sin30 = Math.round(Math.sin(Math.toRadians(30))*100);
    cos60 = Math.round(Math.cos(Math.PI/3)*100);
    tan45 = Math.round(Math.tan(Math.PI/4)*100);
    System.out.println("sin30="+sin30/100);
    System.out.println("cos60="+cos60/100);
    System.out.println("tan45="+tan45/100);
  }
}

//wrong,这个结果有问题
public class SinCosTan {
  public static void main(String[] args) {
    double sin30,cos60,tan45;
    sin30 = Math.sin(Math.toRadians(30));
    cos60 = Math.cos(Math.PI/3);
    tan45 = Math.tan(Math.PI/4);
    System.out.println("sin30="+sin30);
    System.out.println("cos60="+cos60);
    System.out.println("tan45="+tan45);
  }
}

回复列表 (共1个回复)

沙发

可能问题太简单了,大家都不愿意回答,刚才在百度知道上问了一下,回答如下,

首先,Math计算的都是近似值,但是为了得到精确值,就需要做四舍五入的处理,看看Math.round的源代码就知道了:
public static long round(double a) {
return (long)floor(a + 0.5d);
}
round()方法采用了计算机模拟的方法,首先是给参数+0.5再去最近的小数四舍五入。如
sin30=0.49999999999999994,乘以100后=49.999999999999994,再加0.5= 50.49999999999999,再取round()得到,sin30=50.0(四舍五入),这时候,整除100(sin30/100),得到的结果就是精确值0.5了。其他两个数也是同理,此题的关键在round()方法上

我来回复

您尚未登录,请登录后再回复。点此登录或注册