简体   繁体   English

与%运算符混淆

[英]Confused with % operator

I have this simple line of code which shows as remainder 5 : 我有这行简单的代码,显示为余数5

Console.WriteLine(5 % 8);

The % operator shows the remainder after first number and second number are divided. %运算符显示第一个数字和第二个数字相除后的余数。 So, 5 / 8 = 0,625 . 因此, 5 / 8 = 0,625 Shouldn't the reminder of the code above be 6 instead of 5? 上面代码的提示不应该是6而不是5吗? Why do I see 5 when I test in Visual Studio? 在Visual Studio中进行测试时为什么会看到5?

How many times does 8 go "cleanly" into 5? 8“干净地”变成5了多少次? Zero times. 零次。

5 / 8 = 0 (int division)

When you do 5 ÷ 8 , how many items are left over? 当您做5 ÷ 8 ,剩下多少项目? 5. 5。

5 % 8 = 5 (modulus division)

Another way to explain this is: 另一种解释方法是:

You have 5 apples. 你有5个苹果。 Please distribute those apples among 8 groups, but you must ensure that every group has an equal amount of apples. 请在8组中分配这些苹果,但是您必须确保每个组都有相同数量的苹果。

You can't do that. 你不能那样做。 You have less apples than the number of groups. 您的苹果少于分组数目。 You can't give any apples to anyone. 你不能给任何任何苹果。

And because you didn't give any apples away, you are left with 5 apples. 而且由于您没有捐出任何苹果,所以剩下 5个苹果。 That is your remainder. 那是你的余数。

Everything follows from the fundamental rules of integer division. 一切都遵循整数除法的基本规则。 For integers x and y suppose we have: 对于整数xy我们有:

q = x / y;
r = x % y;

The fundamental rules are: 基本规则是:

  • q and r are both integers qr都是整数
  • q * y + r == x
  • Division rounds towards zero when inexact 不精确时,除法将取整为零

Now that you know the fundamental rules you can work out the values of 5 / 8 and 5 % 8 . 现在,您已经了解了基本规则,可以计算出5 / 85 % 8

5 / 8 is an integer. 5 / 8是整数。 The exact value is 0.625 , but that's not an integer, so we round towards zero and get 0 . 确切的值为0.625 ,但这不是整数,因此我们朝零取整并得到0 So q is 0 . 所以q0

To compute r we must solve for q * 8 + r = 5 , which is easy to solve: r = 5 is the solution. 要计算r,我们必须求解q * 8 + r = 5 ,这很容易解决: r = 5是解决方案。

(Note that there are a few more fundamental rules about dividing by zero, and so on, that you usually don't have to worry about.) (请注意,还有一些除零的基本规则,依此类推,您通常不必担心。)

Modulo doesn't give you the first number of the quotient, but the remainder after the second number is divided by the first. 模数不给您商的第一个数字,但是第二个数字后的余数除以第一个。

8 doesn't go into 5 at all, so the remainder is the full 5. 8根本不算入5,所以剩下的就是全部5。

See this answer for several other good explanations: 请参阅此答案以获取其他几个很好的解释:

How does a modulo operation work when the first number is smaller? 第一个数字较小时,模运算如何工作?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM