理解模运算符 % [英] Understanding The Modulus Operator %

查看:48
本文介绍了理解模运算符 %的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根据以下表达式理解模数运算符:

I understand the Modulus operator in terms of the following expression:

7 % 5

这将返回 2,因为 5 进入 7 一次,然后给出剩下的 2,但是当您将此语句反转阅读时,我感到困惑:

This would return 2 due to the fact that 5 goes into 7 once and then gives the 2 that is left over, however my confusion comes when you reverse this statement to read:

5 % 7

这给了我 5 的值,这让我有点困惑.虽然整个 7 没有进入 5,但有一部分是这样的,为什么没有余数或余数为正或负 2?

This gives me the value of 5 which confuses me slightly. Although the whole of 7 doesn't go into 5, part of it does so why is there either no remainder or a remainder of positive or negative 2?

如果它是基于 7 根本不进入 5 的事实来计算 5 的值,为什么余数不是 7 而不是 5?

If it is calculating the value of 5 based on the fact that 7 doesn't go into 5 at all why is the remainder then not 7 instead of 5?

我觉得我对模运算符的理解缺少一些东西.

I feel like there is something I'm missing here in my understanding of the modulus operator.

推荐答案

(此说明仅针对正数,因为其他情况取决于语言)

(This explanation is only for positive numbers since it depends on the language otherwise)

定义

模数是一个数除以另一个数的余数.% 称为模运算.

The Modulus is the remainder of the euclidean division of one number by another. % is called the modulo operation.

例如,9 除以 4 等于 2 但它仍然是 1.这里,9/4 = 29 % 4 = 1.

For instance, 9 divided by 4 equals 2 but it remains 1. Here, 9 / 4 = 2 and 9 % 4 = 1.

在您的示例中:5 除以 7 得到 0 但它仍然是 5 (5 % 7 == 5).

In your example: 5 divided by 7 gives 0 but it remains 5 (5 % 7 == 5).

计算

模运算可以用这个公式计算:

The modulo operation can be calculated using this equation:

a % b = a - floor(a / b) * b

  • floor(a/b) 表示你可以将a除以b
  • 的次数
  • floor(a/b) * b 是成功完全共享的数量
  • 总数 (a) 减去共享的内容等于除法的余数
    • floor(a / b) represents the number of times you can divide a by b
    • floor(a / b) * b is the amount that was successfully shared entirely
    • The total (a) minus what was shared equals the remainder of the division
    • 应用于最后一个例子,这给出:

      Applied to the last example, this gives:

      5 % 7 = 5 - floor(5 / 7) * 7 = 5
      

      模块化算术

      也就是说,你的直觉是它可能是 -2 而不是 5.实际上,在模算术中,-2 = 5 (mod 7) 因为它在 Z 中存在 k 使得 7k - 2 = 5.

      That said, your intuition was that it could be -2 and not 5. Actually, in modular arithmetic, -2 = 5 (mod 7) because it exists k in Z such that 7k - 2 = 5.

      你可能没有学过模算术,但你可能用过角度,并且知道-90°和270°是一样的,因为它是模360.很相似,它环绕!所以拿一个圆,说它的周长是 7.然后你读到哪里是 5.如果你尝试用 10,它应该是 3,因为 10 % 7 是 3.

      You may not have learned modular arithmetic, but you have probably used angles and know that -90° is the same as 270° because it is modulo 360. It's similar, it wraps! So take a circle, and say that it's perimeter is 7. Then you read where is 5. And if you try with 10, it should be at 3 because 10 % 7 is 3.

      这篇关于理解模运算符 %的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆