(注意:与其他问题不同,因为 OP 从未明确指定舍入为 0 或 -Infinity)
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
算术都有一个解决方案。)