Java:如何执行整数除法,使其四舍五入为 -Infinity 而不是 0?
(注意:与此另一个问题不同,因为OP从未明确指定舍入为0或-无穷大)
JLS 15.17.2 表示整数除法四舍五入为零。如果我想要正除数的类似行为(我不关心负除数的行为),那么实现对所有输入的数值正确的最简单的方法是什么?floor()
int ifloor(int n, int d)
{
/* returns q such that n = d*q + r where 0 <= r < d
* for all integer n, d where d > 0
*
* d = 0 should have the same behavior as `n/d`
*
* nice-to-have behaviors for d < 0:
* option (a). same as above:
* returns q such that n = d*q + r where 0 <= r < -d
* option (b). rounds towards +infinity:
* returns q such that n = d*q + r where d < r <= 0
*/
}
long lfloor(long n, long d)
{
/* same behavior as ifloor, except for long integers */
}
(更新:我想有一个解决方案和算术。int
long