回傳最接近陣列平均數的整數(無條件捨去),且不會給空陣列
Return the average of the given array rounded down to its nearest integer.
The array will never be empty.
下列為題目的測試:
(ns marks-test
(:require [clojure.test :refer :all]
[marks :refer :all]))
(deftest simple-test
(is (= (get-average [2, 2, 2, 2]) 2))
(is (= (get-average [1, 5, 87, 45, 8, 8]) 25))
(is (= (get-average [2,5,13,20,16,16,10]) 11))
(is (= (get-average [1,2,15,15,17,11,12,17,17,14,13,15,6,11,8,7]) 11)))
;; (Math/floor m) will return a float & int will coerce to integer
(ns marks)
(defn get-average [marks]
(int (Math/floor (/ (reduce + marks) (count marks))))
)
個別使用後發現其實不需要 Math/floor
就可以達到取整數的目的:
int
取整數Math/floor
無條件捨去,可以用於整數Math/ceil
無條件進位,可以用於整數Math/round
四捨五入,不能用於整數(int 1.3) ;; 1
(int 1.5) ;; 1
(int 1) ;; 1
(Math/floor 1.3) ;; 1.0
(Math/floor 1.5) ;; 1.0
(Math/floor 1) ;; 1.0
(int (Math/floor 1.3)) ;; 1
(int (Math/floor 1.5)) ;; 1
(int (Math/floor 1)) ;; 1
(Math/ceil 1.3) ;; 2.0
(Math/ceil 1.5) ;; 2.0
(Math/ceil 1) ;; 1.0
(int (Math/ceil 1.3)) ;; 2
(int (Math/ceil 1.5)) ;; 2
(int (Math/ceil 1)) ;; 1
(Math/round 1.3) ;; 1
(Math/round 1.5) ;; 2
(Math/round 1.0) ;; 1
(Math/round 1) ;; IllegalArgumentException No matching method found: round clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:80)
;; In this case, int can be used when rounded down to nearest integer
(ns marks)
(defn get-average [marks]
(int (/ (reduce + marks) (count marks))))
;; (quot m n) is the value of m/n, rounded towards 0 to the nearest integer.
;; m, n need not be integers.
(ns marks)
(defn get-average [marks]
(quot (apply + marks) (count marks)))