我想采用一系列用户输入的整数,然后求和输入。例如,如果用户输入:
1 <return>
2 <return>
3 <return>
<return>
6
到目前为止,这是我的代码:
(defun stuff ()
(format t "Enter a number: ")
(let ((n (read)))
(+ n)))
实际上,此示例比应有的示例复杂得多,因为它需要进行多项操作(循环,读取输入和累加)。我将为您提供两种解决方案,一种是简便的方法,另一种是我个人的解决方案。首先简单的方法:
(defun stuff (&optional (acc 0)) ; An optional argument for keeping track of the sum.
(if (y-or-n-p "Do you want to continue?") ; Ask if they want to continue
(progn (format t "Enter a number: ") ; If they say yes we need to ask them for the
(stuff (+ acc (read)))) ; number, read it, add it to the sum, and
; continue. We need progn because we need to
; execute two pieces of code (format and stuff) in the if
acc)) ; If they say no, then return the total sum
我将如何执行更高级的版本:
(defun stuff ()
(loop while (y-or-n-p "Do you want to continue?") ; while they want to continue
do (format t "Enter a number: ") ; print the prompt
sum (parse-integer (read-line)))) ; read the line, parse the integer, and sum it
编辑:上一个版本的版本在新行上停止。
(defun stuff (&optional (acc 0))
(let ((line (read-line)))
(if (string= line "") ; If this line is the empty string
acc ; return the sum
(stuff (+ acc (parse-integer line)))))) ; otherwise recur and sum the number on the line
(defun stuff ()
(loop for line = (read-line)
until (string= line "")
sum (parse-integer line)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句