模数到底是如何工作的?
我知道模数 (%) 的作用,它给出余数。但它是如何做到这一点的呢? 我看到它使用公式:模数=被除数-(被除数/除数)*除数 10%3 应该给你 1(10 是股息,3 是除数) 论坛给出: 10-(10/3)*3 = 10-10 = 0 这显然是错误的。
再说一遍,使用纯变量,股息 - ( 股息 / 除数 ) * 除数 = 股息 - 股息 = 0
我在这里做错了什么? (此外,该公式来自 JASS 的本地语言,JASS 是魔兽争霸 3 游戏中使用的语言)
I know what modulus (%) does, it gives you the remainder. But how does it do that?
I saw that it uses the formula: modulus = dividend - (dividend / divisor) * divisor
10%3 should give you 1 (10 being the dividend and 3 being the divisor)
the forumla gives: 10-(10/3)*3 = 10-10 = 0 which is obviously wrong.
Then again, working with pure variables, dividend - ( dividend / divisor ) * divisor = dividend - dividend = 0
What am I doing wrong here?
(Also, the formula is from a native from JASS, the language used in warcraft 3 games)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
公式
(dividend / divisor)
是计算结果为整数的整数除法。所以,10-(10/3)*3 = 10 - 9 = 1
in the formula
(dividend / divisor)
is an integer division evaluating to an integer.So, 10-(10/3)*3 = 10 - 9 = 1
在许多使用 C、C++、Java 等的编程语言中,10/3 会得到 3,因为除法实际上是整数除法,并且小数部分被截断。
所以,换句话说,n/d 只给你商。
现在,从算术中我们知道任何正整数 n 和任何正整数除数 d, n 都可以表示为:n = q*d + r。如果0≤r<0 n(并且可以证明只有一个小于n的正r),q称为商,r称为余数。
在这些编程语言中,n/d 给出 q。
因此,n - (n/d)*d = n - q*d = r,余数。
In many programming languages using C, C++, Java, etc. 10/3 would result in 3 because divisions are actually integer-divisions and the fractional part is truncated.
So, in other words n/d gives you only the quotient.
Now, from arithmetic we know that any positive integer n and any positive integer divider d, n can be represented as: n = q*d + r. If 0 ≤ r < n (and it can be proven that there is only one such positive r that is less than n), q is called the quotient and r is the called the remainder.
In these programming languages, n/d gives you q.
So, n - (n/d)*d = n - q*d = r, the remainder.