首页 > 编程知识 正文

取模和求余数的区别是什么,取模运算与取余运算的区别

时间:2023-05-03 05:33:35 阅读:275500 作者:4266

取模和求余数的区别 先导知识 fix,向0取整,fix(-3.14) = -3floor,向负无穷取整 ,floor(-3.14) = -4 取模 mod

取模是在模运算的基础上求得的余数

b = mod(a,m),这是matlab的帮助文档

b = mod(a,m) returns the remainder after division of a by m, where a is the dividend and m is the divisor. This function is often called the modulo operation, which can be expressed as b = a - m.*floor(a./m).

mod(a,0) = a

mod(-5,3) = -5 - 3*floor(-5/3) = -5 - 3* (-2) = 1

求余数 rem

求余数是在除法的基础上取得的余数

r = rem(a,b)

r = rem(a,b) returns the remainder after division of a by b, where a is the dividend and b is the divisor. This function is often called the remainder operation, which can be expressed as r = a - b.*fix(a./b).

rem(a,0) = 无穷小量

rem(-5,3) = -5 - 3*fix(-5,3) = -5 - 3*(-1) = -2

此外1,经过测试,在C/C++, C#, JAVA,PHP这几门主流语言中,’%’运算符都是做取余运算,而在python中的’%’是做取模运算[1]。

此外2,余数在数学中的定义是始终大于等于0的,而对于某些编程语言的取余运算不是按照上面的定义来执行的,因此才会出现余数小于0的情况[1]。

因此,在代码移植数值计算的时候要特别小心,这种bug一般是找不出来的。

参考:[1] : https://blog.csdn.net/u012142247/article/details/79445820

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。