C++/Java负数取余(模)

2019-04-14 16:21发布

C++用了些年头,Java刚刚学一个多月。 新的C++11标准对取余有了比较明确的规定: C++ Primer 5th:
The % operator, known as the “remainder” or the “modulus” operator, computes the remainder that results from dividing the left-hand operand by the right-hand operand. The operands to % must have integral type. In a division, a nonzero quotient is positive if the operands have the same sign and negative otherwise. Earlier versions of the language permitted a negative quotient to be rounded up or down; the new standard requires the quotient to be rounded toward zero (i.e., truncated). The modulus operator is defined so that if m and n are integers and n is nonzero, then (m/n)*n + m%n is equal to m. By implication, if m%n is nonzero, it has the same sign as m. Earlier versions of the language permitted m%n to have the same sign as n on implementations in which negative m/n was rounded away from zero, but such implementations are now prohibited. Moreover, except for the obscure case where -m overflows, (-m)/n and m/(-n) are always equal to -(m/n), m%(-n) is equal to m%n,
and (-m)%n is equal to -(m%n). More concretely:
Code:
21 % 6; /* result is 3 */
21 % 7; /* result is 0 */
-21 % -8; /* result is -5 */
21 % -5; /* result is 1 */ 21 / 6; /* result is 3 */
21 / 7; /* result is 3 */
-21 / -8; /* result is 2 */
21 / -5; /* result is -4 */

C++ Primer 4th: For both division (/) and modulus(%), when both operands are positive, the result is positive (or zero). If both operands are negative, the result of division is positive (or zero) and the result of modulus is negative (or zero). If only one operand is negative, then the value of the result is machine-dependent for both operators. The sign is also machine-dependent for modulus; the sign is negative (or zero) for division: 21 % 6; // ok: result is 3 21 % 7; // ok: result is 0 -21 % -8; // ok: result is -5 21 % -5; // machine-dependent: result is 1 or -4 21 / 6; // ok: result is 3 21 / 7; // ok: result is 3 -21 / -8; // ok: result is 2 21 / -5; // machine-dependent: result -4 or -5 When only one operand is negative, the sign and value of the result for the modulus operator can follow either the sign of the numerator or of the denominator. On a machine where modulus follows the sign of the numerator then the value of division truncates toward zero. If modulus matches the sign of the denominator, then the result of division truncates toward minus infinity. 本人实测结果: 编译环境:VS2008 SP1 on Win7 SP1 x64
21 % -5 = 1; 21 / -5 = -4;

Java: 因为Java还是绝对的新手,不知道哪里有Java对取余做的比较明确规范的文档参考。所以只能是在自己的电脑上用编译器做测试: 21 % 6 = 3;
21 % 7 = 0;
-21 % -8 = -5;
21 % -5 = 1;
21 / 6 = 3;
21 / 7 = 3;
-21 / -8 = 2;
21 / -5 = -4
这里测试的结果和C++11要求的结果是一致的。