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);
这只需要 1% 操作 ( and one ternary op
) 并且不需要乘法
如果您使用这些算法中的任何一种并且还需要进行除法,请不要忘记确保在适当的时候减去 1。
IE,
如果-5 % 2 = -1
和-5 / 2 = -2
, 如果 你 关心-5 / 2 * 2 + -5 % 2 = -5
, 那么 当 你 计算 时-5 % 2 = 1
, 那 你 也 计算-5 / 2 = -3
.
使固定 :
(ans=a%b)<0 ? (a<0 && b<0 ? (ans-b)%(-b) : (ans+b)%b) : ans
我知道这个问题不是问的,但我只是编写并测试了一个返回商的方法。我找的时候没找到,所以我想把它放在那里。
/// <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;
}