33

c# 中是否有一个库函数用于数字的数学模数 - 我特别指的是负整数模数正整数应该产生正结果。

编辑以提供示例:

-5 模 3 应该返回 1

4

8 回答 8

29

尝试(a % b) * Math.Sign(a)

试试这个; 它工作正常。

static int MathMod(int a, int b) {
    return (Math.Abs(a * b) + a) % b;
}
于 2010-04-22T13:12:51.220 回答
7
x < 0 ? ((x % m) + m) % m : x % m;
于 2010-04-22T13:26:21.950 回答
4

那么定义(如果我没记错的话)是这样的

a mod b = a - b * floor(a/b)

它可能很慢并且要小心整数除法,就像内置的模数一样:)

其他选项是根据操作数的符号修改内置模数的结果。像这样的东西:

if(a < 0 && b > 0)
{
    return (a % b + b) % b;
}
else if ....
于 2010-04-22T13:26:50.380 回答
2
a < 0 ? ((a+1)%b + b-1) : (a%b);

这只需要 1% 操作 ( and one ternary op) 并且不需要乘法

于 2010-11-29T12:01:22.660 回答
1

如果您使用这些算法中的任何一种并且还需要进行除法,请不要忘记确保在适当的时候减去 1。

IE,

如果-5 % 2 = -1-5 / 2 = -2, 如果 你 关心-5 / 2 * 2 + -5 % 2 = -5, 那么 当 你 计算 时-5 % 2 = 1, 那 你 也 计算-5 / 2 = -3.

于 2010-04-23T01:25:48.033 回答
0

使固定 :

(ans=a%b)<0 ? (a<0 && b<0 ? (ans-b)%(-b) : (ans+b)%b) : ans

于 2010-04-22T16:44:28.800 回答
0

我知道这个问题不是问的,但我只是编写并测试了一个返回商的方法。我找的时候没找到,所以我想把它放在那里。

/// <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;
}
于 2013-08-22T16:06:52.563 回答
-2

可能是 % 运算符?

http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx

于 2010-04-22T13:12:12.157 回答