为什么Math.round返回一个long但Math.floor返回一个double? [英] Why does Math.round return a long but Math.floor return a 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.
- 返回最大(最接近正无穷大)
double
小于或等于参数且等于数学整数的值。 - 与
double ceil(double a)
- 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 along
andrint
rounds to adouble
. 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); butround
andrint
have always had each other the way they are now since the beginning.可以说,也许代替
长圆
和双rint
,它可能是更加一致命名为双轮
和long rlong
,但这是有争议的。也就是说,如果你坚持断然称这是不一致,那么原因可能就像因为它是不可避免的一样令人不满意。Arguably, perhaps instead of
long round
anddouble rint
, it'd be more "consistent" to name themdouble round
andlong 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.
远程相关问题
- 为什么
int num = Integer.getInteger(123)
throwNullPointerException
? - Java Base API中最笨拙/误导性的方法?
- Why does
int num = Integer.getInteger("123")
throwNullPointerException
? - Most awkward/misleading method in Java Base API ?
- Most Astonishing Violation of the Principle of Least Astonishment
Distantly related questions
这篇关于为什么Math.round返回一个long但Math.floor返回一个double?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Returns the closest
- 返回与参数最接近的