【发布时间】:2013-01-21 03:45:17
【问题描述】:
有谁知道一个开源 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 编写一个,发布它,并在此处的答案中链接到它。
【问题讨论】:
-
在 C++11 中有一些,在 Boost 中有更多。不过,我不记得那些范围。
-
可能没有库,因为您可以通过添加 0.5 并强制转换为 int 来获得正常的舍入行为
-
@technosaurus,
std::round也这样做。 -
你为什么要这个?内联并不难:round = (int)(
+0.5), round_down = (int)number 等等。 -
我相信
<math.h>上的大部分功能都有,比如ceil()和floor()
标签: c++ c math int integer-division