1

どういうわけか、乗算関数から奇妙な結果が得られています。これはプログラムです:

(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

正しくないのは乗算だけで、小数を使用する場合のみです。

4

1 に答える 1

5

使用する正規表現"\d+"は、小数点の可能性を考慮せずに、数字のシーケンスに一致します。したがって、最初の乗算の例で1.5は、は2つの別々の数値1ととして処理され、5積全体はとして計算されます。10 * 1 * 5 * 3これは、です150。同様に、2番目の場合は、を取得します654321 * 1 * 5 = 3271605

read-lineを使用する代わりに、空白の結果を分割する方が良いre-seqでしょうか?

于 2012-11-06T07:26:08.010 に答える