问题描述
在Java中,使用%运算符获取整数除以x/y的余数与Math.IEEEremainder(x,y)方法之间在功能或性能上有什么区别吗?
In Java, is there any functional or performance difference between using the % operator to get the remainder of an integer division x / y, and the Math.IEEEremainder( x, y ) method?
推荐答案
除了John B指出的类型差异之外,语义上也存在显着差异. Math.IEEEremainder(x, y)
返回x - n * y
,其中n
是x / y
的最接近整数(在出现平局的情况下取偶数),而x % y
返回x - n * y
,其中是x / y
的整数部分(即n
是将x / y
的真实值四舍五入而不是四舍五入的结果).
Apart from the type difference already pointed out by John B, there's a significant difference in semantics, too. Math.IEEEremainder(x, y)
returns x - n * y
where n
is the closest integer to x / y
(taking the even integer in the case of a tie), while x % y
returns x - n * y
where n
is the integer part of x / y
(i.e., n
is the result of rounding the true value of x / y
towards zero, instead of towards nearest).
为了说明不同之处:Math.IEEEremainder(9.0, 5.0)
将是-1.0
,因为最接近9.0 / 5.0
的整数是2
,而9.0 - 2 * 5.0
是-1.0
.但是9.0 % 5.0
将是4.0
,因为9.0 / 5.0
的整数部分是1
,而9.0 - 1 * 5.0
是4.0
.
To illustrate the difference: Math.IEEEremainder(9.0, 5.0)
would be -1.0
, since the closest integer to 9.0 / 5.0
is 2
, and 9.0 - 2 * 5.0
is -1.0
. But 9.0 % 5.0
would be 4.0
, since the integer part of 9.0 / 5.0
is 1
and 9.0 - 1 * 5.0
is 4.0
.
Here's the official documentation for Math.IEEEremainder
.
这篇关于%运算符和IEEEremainder()方法之间Java的区别(如果有)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!