基本问题:取余运算规则
忘记了,比如对于负数的规定。 问题点数:20、回复次数:4Top
1 楼Riemann()回复于 2003-08-03 17:47:23 得分 5
我的印象中:
a%b=r,r=0,1...r-1
例如(-5)%8,结果应该为3Top
2 楼happy__888([顾问团]寻开心 www.e-jjj.com)回复于 2003-08-04 13:46:44 得分 5
a%b = k*b + d
其中K是整数,D是正整数
和楼上的一样Top
3 楼BlueSky2008(懒惰是程序员的美德)回复于 2003-08-04 18:34:58 得分 10
理论上,我也同意楼上两位的看法。
不过在VC++6.0中,(-k)%n = -(k%n) (k>=0)
所以(-5)%8,结果是-5 :)Top
4 楼BlueSky2008(懒惰是程序员的美德)回复于 2003-08-04 19:02:46 得分 0
找到了,取余结果的绝对值是两个操作数的绝对值的取余结果,取余结果的符号是第一个操作数的符号。(不过这是Microsoft 自己定义的)
下面是MSDN中的原文:
% The result of the remainder operator is the remainder when the first operand is divided by the second. When the division is inexact, the result is determined by the following rules:
If the right operand is zero, the result is undefined.
If both operands are positive or unsigned, the result is positive.
If either operand is negative and the result is inexact, the result is implementation defined. (See the Microsoft Specific section below.)
Microsoft Specific —>
In division where either operand is negative, the direction of truncation is toward 0.
If either operation is negative in division with the remainder operator, the result has the same sign as the dividend (the first operand in the expression).
END Microsoft Specific
Examples
The declarations shown below are used for the following examples:
int i = 10, j = 3, n;
double x = 2.0, y;
This statement uses the multiplication operator:
y = x * i;
In this case, x is multiplied by i to give the value 20.0. The result has double type.
n = i / j;
In this example, 10 is divided by 3. The result is truncated toward 0, yielding the integer value 3.
n = i % j;
This statement assigns n the integer remainder, 1, when 10 is divided by 3.
Microsoft Specific —>
The sign of the remainder is the same as the sign of the dividend. For example:
50 % -6 = 2
-50 % 6 = -2
In each case, 50 and 2 have the same sign.
END Microsoft Specific
Top



