Programming Fundamentals/Conditions/Clojure
conditions.clj
edit;; This program asks the user to select Fahrenheit or Celsius conversion
;; and input a given temperature. Then the program converts the given
;; temperature and displays the result.
;;
;; References:
;; https://www.mathsisfun.com/temperature-conversion.html
(defn get-choice []
(println "Enter C to convert to Celsius or F to convert to Fahrenheit:")
(let [choice (read-line)]
choice))
(defn get-temperature [choice]
(println "Enter" choice "temperature:")
(let [temperature (Float/parseFloat (read-line))]
temperature))
(defn display-error []
(println "You must enter C to convert to Celsius or F to convert to Fahrenheit."))
(defn calculate-celsius [temperature]
(let [result (-> temperature
(- 32)
(* 5)
(/ 9))]
result))
(defn calculate-fahrenheit [temperature]
(let [result (-> temperature
(* 9)
(/ 5)
(+ 32))]
result))
(defn display-result [temperature from-label result to-label]
(println (str temperature "° " from-label "is " result "° " to-label ".")))
(defn main []
(let [choice (get-choice)]
(cond
(or (= choice "C") (= choice "c"))
(let [temperature (get-temperature "Fahrenheit")
result (calculate-celsius temperature)]
(display-result temperature "Fahrenheit" result "Celsius"))
(or (= choice "F") (= choice "f"))
(let [temperature (get-temperature "Celsius")
result (calculate-fahrenheit temperature)]
(display-result temperature "Celsius" result "Fahrenheit"))
:else
(display-error))))
(main)
Try It
editCopy and paste the code above into one of the following free online development environments or use your own Clojure compiler / interpreter / IDE.