为什么-2%360在c#中给出-2而不是358#

时间:2011-09-26 19:32:14

标签: c# .net math

微软数学和谷歌的计算器给我358 -2%360,但C#和Windows计算器输出-2 ......这是正确的答案?

6 个答案:

答案 0 :(得分:12)

C#编译器正在根据C#规范做正确的事情,该规范说明整数:

  

x % y的结果是x – (x / y) * y生成的值。

请注意,(x/y)始终围绕 towards zero

有关如何计算二进制和十进制浮点数的余数的详细信息,请参阅规范的第7.8.3节。

这是否是您的“正确答案”取决于您查看余数操作的方式。其余部分必须满足以下标识:

dividend = quotient * divisor + remainder

我说清楚-2%360是-2。为什么?好吧,首先问问自己商是什么。 360进入-2的次数是多少?显然是零次! 360根本不会进入-2。如果商为零,那么余数必须为-2才能满足同一性。如果360总共-1次进入-2次,其余为358次,你会觉得奇怪吗?

答案 1 :(得分:7)

  

哪个是正确的答案?

两个答案都是正确的。这只是一个常规问题,即返回值。

答案 2 :(得分:3)

答案 3 :(得分:3)

我在http://mathforum.org/library/drmath/view/52343.html

找到了这个非常容易理解的解释
There are different ways of thinking about remainders when you deal 
with negative numbers, and he is probably confusing two of them. The 
mod function is defined as the amount by which a number exceeds the 
largest integer multiple of the divisor that is not greater than that 
number. In this case, -340 lies between -360 and -300, so -360 is the 
greatest multiple LESS than -340; we subtract 60 * -6 = -360 from -340 
and get 20:

-420 -360 -300 -240 -180 -120  -60   0   60   120  180  240  300  360
--+----+----+----+----+----+----+----+----+----+----+----+----+----+--
       | |                                                    |  |
   -360| |-340                                             300|  |340
       |=|                                                    |==|
        20                                                     40

Working with a positive number like 340, the multiple we subtract is 
smaller in absolute value, giving us 40; but with negative numbers, we 
subtract a number with a LARGER absolute value, so that the mod 
function returns a positive value. This is not always what people 
expect, but it is consistent.

If you want the remainder, ignoring the sign, you have to take the 
absolute value before using the mod function.
彼得森博士,数学论坛 http://mathforum.org/dr.math/

答案 4 :(得分:0)

IMO,-2更易于理解和编码。如果你将-2除以360,你的答案就是0余数-2 ......正如将2除以360是0余数2.考虑358也是-2 mod 360的余数并不是很自然。

答案 5 :(得分:0)

来自wikipedia

  

如果余数不为零,则有两种可能的选择   余数,一个是负数,另一个是正数,还有两个   商的可能选择。通常,在数论中,   总是选择正余数,但编程语言选择   取决于语言和a和n的标志。[2]但是,帕斯卡尔   并且Algol68不满足负除数的这些条件,并且   某些编程语言(如C89)甚至不定义结果   n或a中的任何一个都是负数。