C/C++模运算(正负整数)

模运算

模运算:又称为取余运算

正整数的模运算

对于正整数a,b
如果\(a=q\times b+r\)其中\(0\le r < b\)
则有\(a \bmod b=r\)\(a\%b=r\)

负整数的模运算

不同的语言的负数取模运算不一样,
这一个涉及到取整函数tranc和floor

tranc函数:向0取整

例如C/C++,java中采用的是tranc
\( r=a-b\times tranc(\cfrac{a}{b}) \)

floor函数:向负无穷取整

而python中采用的就是floor
\(r=a-b\times \lfloor \cfrac{a}{b} \rfloor\)

C/C++中计算-6%5的过程为

-6 - (5*trunc(-6/5))= -6 - (5 * -1) = -1

python中计算-6%5的过程为

-6 - (5*floor(-6/5))= -6 - (5 * -2) = 4

取整函数不大理解的可以见四种取整函数

posted @ 2020-11-09 22:36  幽灵轩  阅读(725)  评论(0编辑  收藏  举报