问题描述
我在 VHDL 编程中遇到了这些语句,无法理解 mod 和 rem 两个运算符之间的区别
I came across these statements in VHDL programming and could not understand the difference between the two operators mod and rem
9 mod 5
(-9) mod 5
9 mod (-5)
9 rem 5
(-9) rem 5
9 rem (-5)
推荐答案
查看不同之处的一种方法是在测试台上运行快速模拟,例如使用如下流程的示例:
A way to see the different is to run a quick simulation in a test bench, forexample using a process like this:
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 operationhas an elaborate description, including the rules:
- mod 有除数的符号,因此
n
在a mod n
- rem 有被除数,因此
a
在a rem n
- mod has sign of divisor, thus
n
ina mod n
- rem has sign of dividend, thus
a
ina rem n
mod
运算符给出向下舍入的除法的余数(下除法),所以 a = floor_div(a, n) * n + (a mod n)
.优点是 a mod n
是一个重复的锯齿图,当 a
增加甚至通过零时,这在某些计算中很重要.
The mod
operator gives the residue for a division that rounds down (floored division), so a = floor_div(a, n) * n + (a mod n)
. The advantage is that a mod n
is a repeated sawtooth graph when a
is increasing even through zero, which is important in some calculations.
rem
运算符给出向 0(截断除法)舍入的常规整数除法 a/n
的余数,所以 a = (a/n) * n + (a rem n)
.
The rem
operator gives the remainder for the regular integer division a / n
that rounds towards 0 (truncated division), so a = (a / n) * n + (a rem n)
.
这篇关于VHDL中的mod和rem运算符之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!