C#模数运算符

问题描述 投票:19回答:7

我可以写程序

int a = 3;
int b = 4;

Console.WriteLine(a % b);

我得到的答案是3. 3 mod 4 = 3怎么样?

我无法弄清楚这是如何以这种方式计算的。

c# modulus
7个回答
48
投票

因为剩下的3/4 = 3。

http://en.wikipedia.org/wiki/Modulo_operator

如果你不明白为什么余数是3,我们在这里有一些more serious problems


52
投票

我不太清楚会发生什么,但我无法弄清楚其余部分是3。

所以你有3个饼干,你想在4个人之间平均分配它们。

因为有更多的人而不是cookie,没有人得到一个cookie(商= 0),你自己剩下3个饼干。 :)


16
投票

3 mod 4是3除以4时的余数。

在这种情况下,4进入3次零次,余数为3次。


2
投票

正如其他人所解释的那样,但如果你不想使用“mod”运算符。这是计算“a”的余数除以“n”的等式

a-(n* int(a/n))


1
投票

我已经认为用户可能已经理解了答案..因为有这么多优秀的程序员...在简单的措辞中%用你自己的整数划分后告诉你提醒。

EG

int a = int.parse(console.readline());
int b = a % 2;

现在你输入13,它将给出1,因为潜水后13比2的余数在简单的数学中是1。希望你能得到。


0
投票

另一个“正如其他人所解释的”,但如果你对几种模数的方法(或使用另一种方法)感到好奇,你可以read this article which benchmarks a few different ways

基本上,最快的方法是良好的老式模数运算符,类似于:

if (x % threshold == some_value)
{
    //do whatever you need to
}

0
投票

我发现答案令人困惑和误导.....

模数是将第二个数字尽可能多地分成第一个数字后留下的数字。

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
© www.soinside.com 2019 - 2024. All rights reserved.