我在VHDL编程中遇到过这些语句,无法理解两个运算符mod和rem
之间的区别 9 mod 5
(-9) mod 5
9 mod (-5)
9 rem 5
(-9) rem 5
9 rem (-5)
答案 0 :(得分:25)
一种看待不同的方法是在测试台上运行快速模拟 示例使用这样的过程:
process is
begin
report " 9 mod 5 = " & integer'image(9 mod 5);
report " 9 rem 5 = " & integer'image(9 rem 5);
report " 9 mod (-5) = " & integer'image(9 mod (-5));
report " 9 rem (-5) = " & integer'image(9 rem (-5));
report "(-9) mod 5 = " & integer'image((-9) mod 5);
report "(-9) rem 5 = " & integer'image((-9) rem 5);
report "(-9) mod (-5) = " & integer'image((-9) mod (-5));
report "(-9) rem (-5) = " & integer'image((-9) rem (-5));
wait;
end process;
它显示结果:
# ** Note: 9 mod 5 = 4
# ** Note: 9 rem 5 = 4
# ** Note: 9 mod (-5) = -1
# ** Note: 9 rem (-5) = 4
# ** Note: (-9) mod 5 = 1
# ** Note: (-9) rem 5 = -4
# ** Note: (-9) mod (-5) = -4
# ** Note: (-9) rem (-5) = -4
Wikipedia - Modulo operation 有详尽的描述,包括规则:
n
a mod n
a
a rem n
mod
运算符为舍入(浮动除法)的除法提供余数,因此a = floor_div(a, n) * n + (a mod n)
。优点是a mod n
是a
即使在零增加时重复的锯齿图,这在某些计算中很重要。
rem
运算符给出了向0(截断除法)舍入的常规整数除a / n
的余数,因此a = (a / n) * n + (a rem n)
。
答案 1 :(得分:0)
For equal sign:
9/5=-9/-5=1.8 gets 1
9 mod 5 = 9 rem 5
-9 mod -5 = -9 rem -5
-----------------------------------------
For unequal signs:
9/-5 = -9/5 = -1.8
In "mod" operator : -1.8 gets -2
In "rem" operator : -1.8 gets -1
----------------------------------------
example1: (9,-5)
9 = (-5*-2)-1 then: (9 mod -5) = -1
9 = (-5*-1)+4 then: (9 rem -5) = +4
----------------------------------------
example2: (-9,5)
-9 = (5*-2)+1 then: (-9 mod 5) = +1
-9 = (5*-1)-4 then: (-9 rem 5) = -4
----------------------------------------
example3: (-9,-5)
-9 = (-5*1)-4 then: (-9 mod -5) = -4
-9 = (-5*1)-4 then: (-9 rem -5) = -4
----------------------------------------
example4: (9,5)
9 = (5*1)+4 then: (9 mod 5) = +4
9 = (5*1)+4 then: (9 rem 5) = +4