我們對C的%運算知多少呢?
當是正整數時,可能大家都知道。例如:5%3等于2, 3%5等于3。
當存在負數時呢?先看看例子:
例一:
int main()
{
int x;
x = -6%5; printf("%2d/n",x);
x = 6%-5; printf("%2d/n",x);
x = 1%-5; printf("%2d/n",x);
x = -1%-5; printf("%2d/n",x);
x = -6%-5; printf("%2d/n",x);
}
運行結果為:
-1
1
1
-1
-1
例二:
#include int main()
{
int x;
x = 5%-6; printf("%2d/n",x);
x = -5%6; printf("%2d/n",x);
x = 4%5;?? printf("%2d/n",x);
x = -4%-5; printf("%2d/n",x);
x = -5%-6; printf("%2d/n",x);
}
運行結果為:
5
-5
4
-4
-5
你看出規律了嗎?我幫你總結一下:
余數的定義:當被除數不夠整除時余下的數。
當都是正整數時:除法實際可轉化為減數,不夠減時剩下的就是余數。
例如:12%5
12-5-5
2
當存在負數時: x%y
i. 當異號時:???????????????? if |x|>|y|
result: x+y
else
result: x
例:
-6% 5等于-1
6%-5等于 1
5%-6等于 5
-5% 6等于 -5
ii. 當同號時:??????????????? if |x|>|y|
result: x-y
else
result: x
例:
-1%-5等于-1
-6%-5等于-1
-4%-5等于-4
-5%-6等于-5
相信當你記住這個規律后,再遇到這種問題,你不用思考就可以回答出來。
但你一定不會滿意,因為這不是你想要的結果,你一定覺得還有更深層的
原因。如果你感興趣,請接著看:
例三:
#include int main()
{
int x;
x = -6/5; printf("%2d/n",x);
x = 6/-5; printf("%2d/n",x);
x = 1/-5; printf("%2d/n",x);
x = -1/-5; printf("%2d/n",x);
x = -6/-5; printf("%2d/n",x);
}
運行結果:
-1
-1
0
0
1
例四:
#include int main()
{
int x;
x = 5/-6; printf("%2d/n",x);
x = -5/6; printf("%2d/n",x);
x = 4/5;?? printf("%2d/n",x);
x = -4/-5; printf("%2d/n",x);
x = -5/-6; printf("%2d/n",x);
}
運行結果:
0
0
0
0
0
這兩個例子我想大家都覺得很簡單,但簡單并不代表它沒價值,
特別是它和其它事物聯系其來時你才會注意到。
“/”在我們這些程序中代表整除,它符合除法法則,異號抵消。
再看看我們余數的定義:
整除“余”下的“數”。則有:余數=被除數-商*除數商就是我們整除的結果。
看例子:
eg1:
(-6%5) = -6 - (-6/5)*5
(-6%5) = -6 - (-1)*5
(-6%5) = -6 - (-5)
(-6%5) = -6+5
(-6%5) = -1
eg2:
(5%-6) =?? 5 - (5/-6)*(-6)
(5%-6) =?? 5 - (0)*(-6)
(5%-6) =?? 5 - 0
(5%-6) =?? 5
eg3:
(-5%-6)= -5 - (-5/-6)*(-6)
(-5%-6)= -5 - (0)*(-6)
(-5%-6)= -5 - 0
(-5%-6)= -5
eg4:
(6%-5) =?? 6 - (6/-5)*(-5)
(6%-5) =?? 6 - (-1)*(-5)
(6%-5) =?? 6 - 5
(6%-5) =?? 1
到現在為止,你還有什么疑惑?
但我還是有點不明白,這是數學中的定義嗎?
我查了一下《Concrete Mathematics》,請看原文:
摘之 P82
------------------
3.4 ‘MOD': THE BINARY OPERATION
The quotient of n divided by m is [n/m],when m and n are positive
integers. It's handy to have a simple notation also for the remainder
of this division, and we call it 'n mod m', The basic formula
n = m[n/m]+ n mod m
//NOTE:"m[n/m]" is quotient, "n mod m" is remainder
tells us that we can express n mod m as n-m[n/m] .We can generalize this
to megative integers, and in fact to arbitrary real numbers:
x mod y = x - y[x/y], for y!=0.
--------------------
從文中可能看出,數學中的 余數(remainder) 其實就是 取模(mod),即:
x mod y = x%y
x%y???? = x - y[x/y], for y!=0.
數學中的余數概念和我們的計算機中的余數概念一致,但實現卻不一致。
其中 [x/y] 代表的是 x/y 的最小下界。
例:
-3 mod 2???????? = -3 - 2*[-3/2]
= -3 - 2*[-1.5]
= -3 - 2*(-2)
= -3 + 4
= 1
而我們的計算機是怎么做的呢:
-3%2??????? = -3 - 2*(-3/2)
= -3 - 2*(-1)
= -3 - (-2)
= -1
所以計算機中的取余實際上是:
x%y = x - y(x/y), for y!=0.
這就是二者的區別。這個區別,對于正數,二者計算出的結果是相等的,但是負數就不相等了。這就意味著,如果以后在使用數學中余數相關定理的時候,要注意計算機中余數的計算和數學定義不是完全一致的,所以在計算機上,對于負數,數學定理并不完全適用。當然,對于正數,二者是沒有區別的。至于為什么計算機上要這么實現,我想恐怕還是歷史原因,最早的計算機如果這樣計算除法(取余是靠除法來完成的),那么就涉及到浮點數的計算以及取下界,這樣,將比較大的降低效率,所以實現成了這樣的方式,一直沿用至今。