有谁知道一个开源 C 或 C++ 库,其中的函数实现了人们可能想要的每种整数除法模式?可能的行为(对于积极的结果):
round_down, round_up,
round_to_nearest_with_ties_rounding_up,
round_to_nearest_with_ties_rounding_down,
round_to_nearest_with_ties_rounding_to_even,
round_to_nearest_with_ties_rounding_to_odd
每个(除了四舍五入和四舍五入)都有两个变体
// (round relative to 0; -divide(-x, y) == divide(x, y))
negative_mirrors_positive,
// (round relative to -Infinity; divide(x + C*y, y) == divide(x, y) + C)
negative_continuous_with_positive
.
我知道怎么写,但肯定有人已经这样做了吗?
作为一个例子,如果我们假设(这是常见的并且在 C++11 中是强制的)内置有符号整数除法向零舍入,并且内置模数与此一致,那么
int divide_rounding_up_with_negative_mirroring_positive(int dividend, int divisor) {
// div+mod is often a single machine instruction.
const int quotient = dividend / divisor;
const int remainder = dividend % divisor;
// this ?:'s condition equals whether quotient is positive,
// but we compute it without depending on quotient for speed
// (instruction-level parallelism with the divide).
const int adjustment = (((dividend < 0) == (divisor < 0)) ? 1 : -1);
if(remainder != 0) {
return quotient + adjustment;
}
else {
return quotient;
}
}
加分项:适用于多种参数类型;快速地; 也可选择返回模数;不要溢出任何参数值(当然,除以零和 MIN_INT/-1 除外)。
如果我没有找到这样的库,我会用 C++11 编写一个,发布它,并在此处的答案中链接到它。