问题
I can write the program
int a = 3;
int b = 4;
Console.WriteLine(a % b);
The answer I get is 3. How does 3 mod 4 = 3???
I can't figure out how this is getting computed this way.
回答1:
Because the remainder of 3 / 4 = 3.
http://en.wikipedia.org/wiki/Modulo_operator
If you can't figure out why the remainder is 3, we've got some more serious problems here.
回答2:
I wasn't quite sure what to expect, but I couldn't figure out how the remainder was 3.
So you have 3 cookies, and you want to divide them equally between 4 people.
Because there are more people than cookies, nobody gets a cookie (quotient = 0) and you've got a remainder of 3 cookies for yourself. :)
回答3:
3 mod 4 is the remainder when 3 is divided by 4.
In this case, 4 goes into 3 zero times with a remainder of 3.
回答4:
As explained by others, but if you don't want to use the "mod" operator. Here is the equation to figure out the remainder of "a" divided by "n"
a-(n* int(a/n))
回答5:
I already think that the user may have understood the answers. Because there are so many good programmer.. in simple wording % tells you the reminder after dividing with your own integer.
e.g.
int a = int.Parse(Console.ReadLine());
int b = a % 2;
Now your input 13, it will give 1, because after diving 13 by 2 remainder is 1 in simple mathematics. Hope you got that.
回答6:
I found the answer confusing and misleading.....
Modulus is what is left over IN THE FIRST NUMBER after dividing the second into it as many times as possible.
1 % 1 = 0 because after dividing 1 into 1, one time, there's nothing left
2 % 1 = 0 because after dividing 1 into 2, two times, there's nothing left
1 % 2 = 1 because 2 won't go into 1, so 1 is left
回答7:
Another "as explained by others", but if you're curious about several more ways to do modulus (or use an alternative method), you can read this article which benchmarks a few different ways.
Basically, the fastest way is the good old fashioned modulus operator, similar to:
if (x % threshold == some_value)
{
//do whatever you need to
}
来源:https://stackoverflow.com/questions/3427602/c-sharp-modulus-operator