简体   繁体   中英

Clojure multiplication gives strange results

For some reason, I'm getting strange results from a multiplication function. This is the program:

(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))

And these are my results:

 ~/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

The only ones that are incorrect are the multiplications, and only when using decimals.

The regular expression "\\d+" that you use just matches sequence of digits, without allowing for the possibility of a decimal point. So in the first multiplication example, 1.5 is processed as two separate numbers 1 and 5 , and the whole product is computed as 10 * 1 * 5 * 3 , which is 150 . Similarly, for the second, you get 654321 * 1 * 5 = 3271605 .

Might it be better to split the result of read-line on whitespace instead of using re-seq ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM