【问题标题】:Clojure multiplication gives strange resultsClojure 乘法给出了奇怪的结果
【发布时间】:2012-11-06 05:54:01
【问题描述】:

由于某种原因,我从乘法函数中得到了奇怪的结果。这是程序:

(ns scalc.core)

(defn add [numbers]
  (reduce + numbers))

(defn sub [numbers]
  (reduce - numbers))

(defn mul [numbers]
  (reduce * numbers))

(defn div [numbers]
  (reduce / numbers))

(defn numchoose []
  (let [nums (re-seq #"\d+" (read-line))]
    (map #(Float/parseFloat %) nums)))

(defn delegate []
  (println "What operation would you like to do?: ")
  (let [operation (read-line)]

    (when (= operation "add")
      (println "You chose to add.")
      (println "What numbers? ")
      (println (add (numchoose))))

    (when (= operation "mul")
      (println "You chose to multiply.")
      (println "What numbers? ")
      (println (mul (numchoose))))

    (when (= operation "div")
      (println "You chose to divide.")
      (println "What numbers? ")
      (println (div (numchoose))))

    (when (= operation "sub")
      (println "You chose to subtract.")
      (println "What numbers? ")
      (println (sub (numchoose))))))

(defn -main
  [& args]

  (delegate))

这些是我的结果:

 ~/clj/scalc 1/7 % lein trampoline run src/scalc/core.clj
What operation would you like to do?: 
mul
You chose to multiply.
What numbers? 
10 1.5 3
150.0
 ~/clj/scalc 1/7 % lein trampoline run src/scalc/core.clj
What operation would you like to do?: 
mul
You chose to multiply.
What numbers? 
654321 1.5
3271605.0
 ~/clj/scalc 1/7 % lein trampoline run src/scalc/core.clj
What operation would you like to do?: 
add
You chose to add.
What numbers? 
1 2 3 4 5 6
21.0
 ~/clj/scalc 1/7 % lein trampoline run src/scalc/core.clj
What operation would you like to do?: 
sub
You chose to subtract.
What numbers? 
100 90 4
6.0
 ~/clj/scalc 1/7 % lein trampoline run src/scalc/core.clj
What operation would you like to do?: 
div
You chose to divide.
What numbers? 
64 8 2
4.0

唯一不正确的是乘法,并且仅在使用小数时。

【问题讨论】:

    标签: math clojure floating-point calculator multiplication


    【解决方案1】:

    您使用的正则表达式"\d+" 仅匹配数字序列,不允许出现小数点。所以在第一个乘法示例中,1.5 被处理为两个单独的数字15,整个乘积计算为10 * 1 * 5 * 3,即150。同样,对于第二个,您会得到654321 * 1 * 5 = 3271605

    read-line 的结果拆分为空白而不是使用re-seq 会更好吗?

    【讨论】:

    • 谢谢。我明白了,我已经用 split 替换了 re-seq。
    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 2013-12-19
    • 1970-01-01
    相关资源
    最近更新 更多