在Clojure中没有得到整数溢出? [英] Not getting integer overflow in Clojure?
问题描述
我在IntelliJ IDEA中使用La Clojure运行Clojure 1.3.0,同时阅读Clojure的喜悦,在第4.1.3节(第64页)中,作者用下面的代码演示了整数溢出:
I am running Clojure 1.3.0 with La Clojure in IntelliJ IDEA while reading The Joy Of Clojure, and on section 4.1.3 (page 64), the authors demonstrate integer overflow with the following code:
(+ Integer/MAX_VALUE Integer/MAX_VALUE)
;=> java.lang.ArithmeticException: integer overflow
但是,当我在REPL上尝试时,
However, when I try it out on the REPL, I get instead
user=> (+ Integer/MAX_VALUE Integer/MAX_VALUE)
4294967294
user=> Integer/MAX_VALUE
2147483647
这里发生了什么?
推荐答案
(已编辑) Clojure 1.3.0)自动将整数转换为长整型。有关Clojure 1.3.0中自动装箱,升级和原生数值类型支持的详细信息,请查看文档Clojure 1.3.0数字。
(edited) Clojure (at least 1.3.0) automatically converts the integer to a long if necessary. For more details about automatic boxing, promotion and primitive numeric type support in Clojure 1.3.0 check the Documentation for Clojure 1.3.0 Numerics.
没有溢出的原因是因为Clojure自动将整数转换为长整型,所以(+ Integer / MAX_VALUE Integer / MAX_VALUE)
添加两个长整型:
The reason you don't get an overflow is because Clojure automatically converts the integer to a long, so (+ Integer/MAX_VALUE Integer/MAX_VALUE)
is adding two longs:
user> (type Integer/MAX_VALUE)
java.lang.Long
这篇关于在Clojure中没有得到整数溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!