c# 整数除法取整_如何在C#中计算整数的除法和取模?

有趣的事实!

“取模”操作定义为:

a % n ==> a - (a/n) * n

因此,您可以自己滚动,尽管它的FAR速度比内置的%运算符慢:

public static int Mod(int a, int n)

{

return a - (int)((double)a / n) * n;

}

编辑:哇,原来这里很不对劲,谢谢@joren抓住了我

现在,在这里我依靠的事实是,C#中的除法+强制转换为int等效于Math.Floor(即,它除去了分数),但是“真正的”实现将是这样的:

public static int Mod(int a, int n)

{

return a - (int)Math.Floor((double)a / n) * n;

}

实际上,您可以通过以下方法查看%和“真实模量”之间的差异:

var modTest =

from a in Enumerable.Range(-3, 6)

from b in Enumerable.Range(-3, 6)

where b != 0

let op = (a % b)

let mod = Mod(a,b)

let areSame = op == mod

select new

{

A = a,

B = b,

Operator = op,

Mod = mod,

Same = areSame

};

Console.WriteLine("A B A%B Mod(A,B) Equal?");

Console.WriteLine("-----------------------------------");

foreach (var result in modTest)

{

Console.WriteLine(

"{0,-3} | {1,-3} | {2,-5} | {3,-10} | {4,-6}",

result.A,

result.B,

result.Operator,

result.Mod,

result.Same);

}

结果:

A B A%B Mod(A,B) Equal?

-----------------------------------

-3 | -3 | 0 | 0 | True

-3 | -2 | -1 | -1 | True

-3 | -1 | 0 | 0 | True

-3 | 1 | 0 | 0 | True

-3 | 2 | -1 | 1 | False

-2 | -3 | -2 | -2 | True

-2 | -2 | 0 | 0 | True

-2 | -1 | 0 | 0 | True

-2 | 1 | 0 | 0 | True

-2 | 2 | 0 | 0 | True

-1 | -3 | -1 | -1 | True

-1 | -2 | -1 | -1 | True

-1 | -1 | 0 | 0 | True

-1 | 1 | 0 | 0 | True

-1 | 2 | -1 | 1 | False

0 | -3 | 0 | 0 | True

0 | -2 | 0 | 0 | True

0 | -1 | 0 | 0 | True

0 | 1 | 0 | 0 | True

0 | 2 | 0 | 0 | True

1 | -3 | 1 | -2 | False

1 | -2 | 1 | -1 | False

1 | -1 | 0 | 0 | True

1 | 1 | 0 | 0 | True

1 | 2 | 1 | 1 | True

2 | -3 | 2 | -1 | False

2 | -2 | 0 | 0 | True

2 | -1 | 0 | 0 | True

2 | 1 | 0 | 0 | True

2 | 2 | 0 | 0 | True

你可能感兴趣的:(c#,整数除法取整)