为什么模运算符的行为与数学派MOD不同

时间:2016-08-31 11:36:03

标签: c# math division modular-arithmetic

如下图所示,在负数除以负数时,常用方法和编程方法之间存在异常。

异常的数学演示:(抱歉手写不好:)希望它是可读的) Division Anomaly (Mathematical Demonstration)

C#在两个负数之间划分的方法: Division Anomaly (C# Approach)

当我用通常的语法划分两个负数时,如何强制C#遵循分数概念?请不要建议我使用以下算法:

// 'num1' and 'num2' are the two numbers of 'int' data-type to be divided where Math.Abs(num1) > Math.Abs(num2)
if (num1<0 && num2<0)  // both numbers are negative
    Console.WriteLine(Math.Abs(num1)%Math.Abs(num2)); 
else 
    Console.WriteLine(num1%num2);

PS:请注意,关于两个负数之间的区分产生的两个答案的数学异常,不需要详细说明。只是建议我一种方法来强制C#遵循上面提到的分数概念(如果可能的话)。

PPS:解释为什么编程语言遵循正常的划分方法而不是分数概念也会有所帮助:)

编辑:上面的C#方法图片代码(适用于难以阅读的图片的人:) :)

// Tests to see C#'s return values for signed and unsigned "modular division"
Console.WriteLine("-10 MOD 3 = "+ ((-10)%(3))); // Displays -1 (as expected)
Console.WriteLine("10 MOD -3 = "+ ((10)%(-3))); // Displays 1 (as expected)
Console.WriteLine("10 MOD 3 = "+ ((10)%(3))); // Displays 1 (as expected)
Console.WriteLine("-10 MOD -3 = "+ ((-10)%(-3))); // Displays -1 (should have displayed a positive 1)

Console.WriteLine("-10 MOD -3 (with no brackets placed for numbers) = "+ (-10%-3)); // Same output as that of above statement i.e. -1

更新:考虑到Stack Overflow社区的意见,我认为没有任何编程语言可以遵循“分数概念”。但欢迎社区中的任何人就“为什么编程语言采用'划分方法'?”提出意见?题。如果有人在不久的将来找到了在C#中强制执行“分数概念”的方法,请发布解决方案。谢谢。 :)

1 个答案:

答案 0 :(得分:3)

(-10) % (-3) = ( (-9)          + (-1) ) % (-3) 
             = ( 3*(-3)        + (-1) ) % (-3) 
             = (3*(-3)) % (-3) + (-1) % (-3) 
             = 0 + (-1) % (-3)

so -10 mod -3 = -1 mod -3

please compare with the spec of C#'s % operator...

Note that as mathematician, i would not do a mod b with b<0...