[英]Mathematical modulus in c#
在c#中是否有一個庫函數用於數字的數學模數 - 由此我特別指的是以正整數為模的負整數應該產生正結果。
編輯提供一個例子:
-5模3應該返回1
嘗試
(a % b) * Math.Sign(a)
嘗試這個; 它工作正常。
static int MathMod(int a, int b) {
return (Math.Abs(a * b) + a) % b;
}
x < 0 ? ((x % m) + m) % m : x % m;
那么定義(如果我沒有記錯的話)是這樣的
a mod b = a - b * floor(a / b)
它可能非常慢,並提防整數除法就像內置模數:)
其他選項是根據操作數的符號修改內置模數的結果。 像這樣的東西:
if(a < 0 && b > 0)
{
return (a % b + b) % b;
}
else if ....
a < 0 ? ((a+1)%b + b-1) : (a%b);
這只需要一個%的操作( and one ternary op
)並且不需要乘法
如果您正在使用這些算法中的任何一種,並且您還需要進行除法,請不要忘記確保在適當時減去1。
也就是說,
如果-5 % 2 = -1
且-5 / 2 = -2
,如果你關心-5 / 2 * 2 + -5 % 2 = -5
,那么當你計算-5 % 2 = 1
,那個你也算-5 / 2 = -3
。
我知道問題沒有要求它,但我只是編寫並測試了一個返回商的方法。 當我在尋找它時沒有找到它,所以我想我會把它放在那里。
/// <summary>
/// Compute integer quotient and remainder of <paramref name="dividend"/> / <paramref name="divisor"/>
/// where the <paramref name="remainder"/> has the same sign as <paramref name="divisor"/>, and is
/// between zero (inclusive) and the <paramref name="divisor"/> (exclusive). As always,
/// (quotientResult * <paramref name="divisor"/> + <paramref name="remainder"/> == <paramref name="dividend"/>).
/// </summary>
public static int DivRemPeriodic(int dividend, int divisor, out int remainder) {
var quotient = Math.DivRem(dividend, divisor, out remainder);
if (divisor > 0 ? remainder < 0 : remainder > 0) {
remainder += divisor;
quotient -= 1;
}
return quotient;
}
修復:
(ans = a%b)<0? (a <0 && b <0?(ans-b)%( - b):( ans + b)%b):ans
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.