这是我所做的:
#include <stdio.h>
#include <limits.h>
int ThreeFourths(int x)
{
int x3 = x + x + x;
return (x3 >= 0) ? (x3 >> 2) : -(int)((UINT_MAX - x3 + 1) >> 2);
}
int testData[] =
{
0,
1,
-1,
2,
-2,
3,
-3,
4,
-4,
5,
-5,
-9,
11,
INT_MAX / 2 + 1,
INT_MIN
};
int main(void)
{
int i;
for (i = 0; i < sizeof(testData)/sizeof(testData[0]); i++)
{
printf(" %d * 3 / 4 = %d\n",
testData[i], testData[i] * 3 / 4);
printf("ThreeFourths(%d) = %d\n",
testData[i], ThreeFourths(testData[i]));
}
return 0;
}
输出:
0 * 3 / 4 = 0
ThreeFourths(0) = 0
1 * 3 / 4 = 0
ThreeFourths(1) = 0
-1 * 3 / 4 = 0
ThreeFourths(-1) = 0
2 * 3 / 4 = 1
ThreeFourths(2) = 1
-2 * 3 / 4 = -1
ThreeFourths(-2) = -1
3 * 3 / 4 = 2
ThreeFourths(3) = 2
-3 * 3 / 4 = -2
ThreeFourths(-3) = -2
4 * 3 / 4 = 3
ThreeFourths(4) = 3
-4 * 3 / 4 = -3
ThreeFourths(-4) = -3
5 * 3 / 4 = 3
ThreeFourths(5) = 3
-5 * 3 / 4 = -3
ThreeFourths(-5) = -3
-9 * 3 / 4 = -6
ThreeFourths(-9) = -6
11 * 3 / 4 = 8
ThreeFourths(11) = 8
1073741824 * 3 / 4 = -268435456
ThreeFourths(1073741824) = -268435456
-2147483648 * 3 / 4 = -536870912
ThreeFourths(-2147483648) = -536870912
我不对负整数使用右移的原因很简单。这些移位的结果是实现定义的(根据 C 标准),并且不能保证与我们可能期望的带有符号扩展的右移位相同,因为它是最常见的实现。
我写(UINT_MAX - x3 + 1)
而不是仅仅-x3
因为它会导致有符号溢出(当x3
=INT_MIN
是 2 的负幂时),它具有未定义的行为(再次按照 C 标准)。即使已知这种未定义的行为是无害的,简单的否定仍然可能无法产生正数(因为有符号整数的 2 的补码表示中的不对称性)。
x + x + x
仍然可以产生有符号溢出x * 3
。因此,这是相同的未定义行为。
顺便说一句,由于签名溢出会导致 UB,因此甚至不应该在法律上要求您实现它们,更不用说对 UB 发生时的结果有具体的期望了。