gpt4 book ai didi

clojure - Clojure 中的简单猜谜游戏无法正常运行

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:29 25 4
gpt4 key购买 nike

我是 Clojure 新手。作为练习的一部分,我编写了一个简单的猜谜游戏,用户必须猜测程序选择的 1-100 之间的随机数。我得到了一个基本版本(代码片段 1)。现在我想通过允许用户输入 1 到 100 之间的整数来对此进行改进。但是我为避免用户输入字符串而编写的代码不起作用(代码片段 2)但是代码不起作用,不不管我怎么努力。

代码片段 1(有效)

(ns guessing-game2.core
(:gen-class))

(defn -main []
(let [my-number (inc (rand-int 100))]
(println "I have a number between 1 and 100, guess it: ")
(loop [times 1]
(let [guess (Integer/parseInt (read-line))]
(if (= guess my-number)
(do
(println "You have found it in " times " tries!")
times)

(do
(cond
(< guess my-number) (println "My number is bigger, guess again: ")
(> guess my-number) (println "My number is smaller, guess again: "))
(recur (inc times))))))))

代码片段 2(无效)

(ns guessing-game.core
(:gen-class))

(defn -main []
(let [my-number (inc (rand-int 100))]
(println "I have a number between 1 and 100, guess it: ")
(loop [times 1]
(let [guess (Integer/parseInt (read-line))]
(if (and (integer? guess)
(< guess 100))
(if (= guess my-number)
(do
(println "You have found it in " times " tries!")
times)

(do
(cond
(< guess my-number) (println "My number is bigger, guess again: ")
(> guess my-number) (println "My number is smaller, guess again: "))))

(print "Please enter a number")
(recur (inc times))

)
))))

最佳答案

你需要在 if 之外recur

(ns guessing-game.core
(:gen-class))

(defn -main []
(let [my-number (inc (rand-int 100))]
(println "I have a number between 1 and 100, guess it: ")
(loop [times 1]
(let [guess (Integer/parseInt (read-line))]
(if (and (integer? guess)
(< guess 100))
(if (= guess my-number)
(do
(println "You have found it in " times " tries!")
times)

(do
(cond
(< guess my-number) (println "My number is bigger, guess again: ")
(> guess my-number) (println "My number is smaller, guess again: "))))

(print "Please enter a number")) ;; <-- moved bracket to here
(recur (inc times))
))))

关于clojure - Clojure 中的简单猜谜游戏无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53672374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com