gpt4 book ai didi

lisp - 使用 Lisp 检查循环中的偶数和奇数

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:13 24 4
gpt4 key购买 nike

我不明白为什么下面的 lisp 程序显示 15 行输出而不是 10 行:

(defparameter x 1)
(dotimes (x 10)
(if (oddp x)
(format t "x is odd~%"))
(format t "x is even~%"))

我在 Windows 10 机器上使用 CLISP 2.49。

最佳答案

除了已接受的答案外,请注意使用自动缩进编辑器(例如使用 Emacs)可以轻松发现这些类型的错误。您的代码自动缩进如下:

(dotimes (x 10)
(if (oddp x)
(format t "x is odd~%"))
(format t "x is even~%"))

if 和第二个 format 表达式垂直对齐(它们是以 dotimes 为根的树中的兄弟),而您希望第二个 format 仅在测试失败时发生,与第一个深度相同。

备注

您还可以分解一些代码:

(format t 
(if (oddp x)
"x is odd~%"
"x is even~%"))

甚至:

(format t
"x is ~:[even~;odd~]~%"
(oddp x))

以上依赖conditional formatting .

关于lisp - 使用 Lisp 检查循环中的偶数和奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56556009/

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