简体   繁体   English

(Java)为什么Math.ceil(15/10)是1.0而不是2.0?

[英](Java) why is Math.ceil(15/10) is 1.0 and not 2.0?

Why is Math.ceil(15/10) 1.0 and not 2.0 ? 为什么Math.ceil(15/10) 1.0而不是2.0? When I run instead Math.ceil((double)15/10) I get 2.0 as expected. 当我改为运行Math.ceil((double)15/10) ,得到的是2.0。

Because dividing an integer by another integer gives you an integer : 15/10 is 1 . 因为将一个整数除以另一个整数可以得到一个整数: 15/101

From the specification : 规格

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| 整数除法朝着0取整。也就是说,在二进制数值提升(第5.6.2节)之后为操作数n和d产生的商是整数值q,其大小应尽可能大,同时满足| d·q | ≤ |n|. ≤| n |。 Moreover, q is positive when |n| 此外,当| n |时q为正。 ≥ |d| ≥| d | and n and d have the same sign, but q is negative when |n| 和n和d具有相同的符号,但是| n |时q为负。 ≥ |d| ≥| d | and n and d have opposite signs. n和d具有相反的符号。

You should use Math.ceil(15.0/10) or Math.ceil(15f/10) (the first one using doubles, the second one float). 您应该使用Math.ceil(15.0/10)Math.ceil(15f/10) (第一个使用双精度,第二个使用浮点)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM