某程序员问:

   给大家出个题,判断一个int值的奇数还是偶数,以下方法可行吗?

     def evenOrNot(i:Int) = i%2 == 1

我不假思索的回答是了,结果负数的时候不是。

晚上跑到个编译器下面 试了一下 -3 % 2,结果如下:

 

python,lua,ruby:

    -3 % 2 = 1

C,scala,erlang 结果如下:

   -3 % 2 = -1

 

居然不一样,网友给出以下回复:

With two choices for the inequality, there are two choices for the remainder, one negative and the other positive. This means that there are also two possible choices for the quotient. In number theory the positive remainder is chosen by convention. But programming languages need not, and different languages have adopted different conventions: C99 and Pascal choose the remainder with the same sign as the dividend a. (Before C99, the C language allowed either choice.)Perl, Python (only modern versions), and Common Lisp choose the remainder with the same sign as the divisor d. Haskell and Scheme offer two functions, remainderand modulo – Fortran has mod and modulo; the former agrees in sign with the dividend, and the latter with the divisor.

 

求翻译后解释如下:

 就是说,余数有正数,负数两种结果。number thory根据习惯全部取正数的余数。

而编程语言则是

1.一部分以被除数的正负号为余数的正负号。

2.一部分则以除数的.......