新手问题 Ruby 为什么要设计成 13/(-3)=-5?

africwildman · 2015年01月12日 · 最后由 yfractal 回复于 2015年01月13日 · 2303 次阅读

这样不是容易搞错吗?

运算符的优先级问题

13/(-3) 不等於 -5 又應該等於多少呢?Int 用 floor 取整就是這樣的。如果要獲得精確數值可以這樣寫 13.0/(-3)

#1 楼 @awking 這個跟優先級恐怕關係不大

楼主你可以算算 1 / 3 * 3

不自动转型,向下取整。

13./ -3 为了符合面向对象的思想?

#6 楼 @yfractal 这样我想到了体现函数式编程思想的 lisp

(/ 13 -3);

C/Java/C# 的 -13/3 = 13/-3 = -4 都是简单的正数除法加个负号

而 Ruby, Python 和 Perl 都是向负无穷规约,商为 -5, 这个设计的优点是被除数为正的时候能保证余数总是非负的

(-13).divmod 3 # 商为 -5, 余 2

在数论上一般都是用非负余数

http://en.wikipedia.org/wiki/Modulo_operation

Usually, in number theory, the positive remainder is always chosen

Raymond T. Boute[6] describes the Euclidean definition, which is the one in which the remainder is always positive or 0, and is therefore consistent with the division algorithm

#8 楼 @luikore ,这几天才复习了 C,但是一直不知道 RUBY 竟然和 C 不同,为了保证余数总是非负的,向负无穷规约。学习了!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号