关于C#:整数除法的行为是什么?

What is the behavior of integer division?

例如,

1
2
3
int result;

result = 125/100;

要么

1
result = 43/100;

结果总会成为师的底线吗? 什么是定义的行为?


Will result always be the floor of the division? What is the defined behavior?

是,两个操作数的整数商。

6.5.5 Multiplicative operators

6 When integers are divided, the result of the / operator is the algebraic quotient with any
fractional part discarded.88) If the quotient a/b is representable, the expression
(a/b)*b + a%b shall equal a.

以及相应的脚注:

88) This is often called ‘‘truncation toward zero’’.

当然要注意的两点是:

3 The usual arithmetic conversions are performed on the operands.

和:

5 The result of the / operator is the
quotient from the division of the
first operand by the second; the
result of the % operator is the
remainder. In both operations, if the
value of the second operand is zero,
the behavior is undefined.

[注意:强调我的]


Dirkgently给出了C99中整数除法的优秀描述,但是您也应该知道在C89中,带有负操作数的整数除法具有实现定义的方向。

从ANSI C草案(3.3.5):

If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

当你遇到C89编译器时,请注意负数。

这是一个有趣的事实,C99选择截断为零,因为这是FORTRAN如何做到的。请参阅comp.std.c上的此消息。


在结果为负的情况下,C截断为0而不是地板 - 我学习了这个解释为什么Python整数除法总是落在这里:为什么Python的整数分区Floors


是的,结果总是被截断为零。它将朝着最小的绝对值四舍五入。

1
2
-5 / 2 = -2
 5 / 2 =  2

对于无符号和非负有符号值,这与floor(向-Infinity舍入)相同。


Will result always be the floor of the division?

不会。结果会有所不同,但只有负值才会发生变化。

What is the defined behavior?

使整数分区朝向负无穷大,同时整数除法向零舍入(截断)

对于正值,它们是相同的

1
2
int integerDivisionResultPositive= 125/100;//= 1
double flooringResultPositive= floor(125.0/100.0);//=1.0

对于负值,这是不同的

1
2
int integerDivisionResultNegative= -125/100;//=-1
double flooringResultNegative= floor(-125.0/100.0);//=-2.0