functionclojureclojure-core.logic

Clojure: How to get an exact answer in a function that calculates the average


How do I get the exact answer instead of just the number / count

I can get the average of a list of numbers, but it will only add the total numbers and divide by the count

(defn aver
  [numbers]
    (if (empty? numbers)
      0
      (/ (reduce + numbers) (count numbers)))
      )

If I am to get the average of a list of [5 10] I'll not get the answer which should be 7.5, I'll only get the equation, how do I get otherwise?

 >(aver [5 10])
=> 15/2

Solution

  • Integer division in Clojure gives you rational numbers. If you want floating point numbers, one of the arguments needs to be a float. Or, you can pass the result to float.

    (float (aver [5 10]))

    `