2012-11-06 83 views
1

出於某種原因,我得到了乘法函數的奇怪結果。這是程序:Clojure乘法給出了奇怪的結果

(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 

只有那些不正確的是乘法,只有當使用小數。

回答

5

您使用的正則表達式"\d+"只是匹配數字序列,不允許有小數點的可能性。因此,在第一個乘法示例中,1.5作爲兩個單獨的數字15進行處理,整個產品計算爲10 * 1 * 5 * 3,即150。同樣,第二,你得到654321 * 1 * 5 = 3271605

將空格read-line的結果拆分而不是使用re-seq可能更好嗎?

+0

謝謝。我明白了,我已經用拆分取代了re-seq。 – Emil