首页 > 解决方案 > Clojure寻找矩形区域

问题描述

(defn -main []
  (println "\nTo compute the area of a rectangle,")
  (print   " enter its width: ") (flush)
  (let [ Width (read) ]
    (assert (>= Width 0) "-main: Width must be positive"))
  (print " enter its height: ") (flush)
  (let [ Height (read) ]
    (assert (>= Height 0) "-main: Height must be positive")
    (printf "\nThe area is %f %f\n\n" (rectangleArea Width Height  ))

我是 Clojure 的新手,每当我尝试编译 printf 函数时都会出现无法解决符号错误

标签: clojure

解决方案


尽管您提供了一个不完整的示例,但经过一些更改后,您的问题似乎是您正在使用%f格式化整数(java.lang.Long):

(defn -main []
  (println "\nTo compute the area of a rectangle,")
  (print   " enter its width: ") (flush)
  (let [ Width (read) ]
    (assert (>= Width 0) "-main: Width must be positive"))
  (print " enter its height: ") (flush)
  (let [ Height (read) ]
    (assert (>= Height 0) "-main: Height must be positive")
    (printf "\nThe area is %f %f\n\n" (+ 10 20  ))))

(-main)
;;=> 
1. Unhandled java.util.IllegalFormatConversionException
   f != java.lang.Long

当然你的 let 块是不正确的,所以它应该更像这样:

(defn- read-size [label]
  (print  " enter its " label ":")
  (flush)
  (let [num (read)]
    (assert (>= num 0) (str  label " must be positive"))
    num))

(defn -main []
  (println "\nTo compute the area of a rectangle,")
  (flush)
  (let [width (read-size "width")
        height (read-size "height")]
    (printf "\nThe area is %d \n\n" (* width height))))


推荐阅读