为什么Math.round返回一个long但Math.floor返回一个double? [英] Why does Math.round return a long but Math.floor return a double?

查看:200
本文介绍了为什么Math.round返回一个long但Math.floor返回一个double?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不一致?

推荐答案

没有不一致之处:方法的设计遵循不同的规范。

There is no inconsistency: the methods are simply designed to follow different specifications.


  • long round(double a)


    • 返回与参数最接近的 long

    • long round(double a)
      • Returns the closest long to the argument.
      • Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
      • Compare with double ceil(double a)

      • 返回 double 值与参数最接近的值,等于数学整数

      • Returns the double value that is closest in value to the argument and is equal to a mathematical integer

      所以通过设计 round 轮到 long rint 轮到 double 。自JDK 1.0以来一直如此。

      So by design round rounds to a long and rint rounds to a double. This has always been the case since JDK 1.0.

      JDK 1.2中添加了其他方法(例如 toRadians toDegrees );其他人在1.5中添加(例如 log10 ulp signum 等等,还有一些在1.6中添加(例如 copySign getExponent nextUp 等)(在文档中查找 Since:元数据);但 round rint 从一开始就一直拥有彼此的方式。

      Other methods were added in JDK 1.2 (e.g. toRadians, toDegrees); others were added in 1.5 (e.g. log10, ulp, signum, etc), and yet some more were added in 1.6 (e.g. copySign, getExponent, nextUp, etc) (look for the Since: metadata in the documentation); but round and rint have always had each other the way they are now since the beginning.

      可以说,也许代替长圆双rint ,它可能是更加一致命名为双轮 long rlong ,但这是有争议的。也就是说,如果你坚持断然称这是不一致,那么原因可能就像因为它是不可避免的一样令人不满意。

      Arguably, perhaps instead of long round and double rint, it'd be more "consistent" to name them double round and long rlong, but this is argumentative. That said, if you insist on categorically calling this an "inconsistency", then the reason may be as unsatisfying as "because it's inevitable".

      这是来自有效的Java第2版,第40项:仔细设计方法签名:


      如有疑问,请查看Java库API作为指导。虽然有很多不一致 - 不可避免,考虑到这些图书馆的规模和范围 - 也有相当多的共识。

      When in doubt, look to the Java library APIs for guidance. While there are plenty of inconsistencies -- inevitable, given the size and scope of these libraries -- there are also fair amount of consensus.



      远程相关问题



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