当我在 Clojure 中除数时,我得到一个分数,我如何得到小数?

当我做 (/ 411 125)的时候,我不是用十进制表示的,我怎么做呢?

31331 次浏览

As documented, integer division yields rational numbers. Try

(/ 411.0 125)

If you use a float for the dividend, you'll get a decimal answer.

(/ 22.0 7) -> 3.142857142857143

There's also the (unchecked-remainder x y) function available.

user> (float (/ 411 125))
3.288
user> (double (/ 411 125))
3.288
user=> (clojure-version)
"1.4.0"


user=> (doc quot)
-------------------------
clojure.core/quot
([num div])
quot[ient] of dividing numerator by denominator.
nil


user=> (quot 411 125)
3

(float 411/125) is another variant if you are given the numbers directly, which is the case if you are just using the REPL as a calculator. Unfortunately this is a few characters longer than the solution by Jonathan Feinberg and ire_and_curses. ;)

even this will work:

(/ 22. 7) => 3.142857142857143