【问题标题】:If condition with and operator如果条件与运算符
【发布时间】:2021-05-07 09:06:18
【问题描述】:

如何将 IF 条件与 AND 运算符一起使用? 我收到一个错误

(princ"Enter a year: ")
(defvar y(read))
(defun leap-year(y)
    (if(and(= 0(mod y 400)(= 0(mod y 4))
       (print"Is a leap year"))
       (print"Is not"))))

(leap-year y)

【问题讨论】:

  • 错误信息很重要,请在描述错误/问题时说明报告了哪个错误

标签: lisp common-lisp clisp


【解决方案1】:

请注意,您的代码理想情况下应如下所示:

(princ "Enter a year: ")
(finish-output)             ; make sure that output is done

(defvar *year*              ; use the usual naming convention for
                            ;  global variables.
  (let ((*read-eval* nil))  ; don't run code during reading
    (read)))

(defun leap-year-p (y)
  ; your implementation here
  ; return a truth value
  )

(print (if (leap-year-p *year*) "yes" "no"))

另外,最好不要在顶层使用函数调用和全局变量。为一切编写程序/函数。这样,您的代码自动变得更加模块化、可测试和可重用。

(defun prompt-for-year ()
  (princ "Enter a year: ")
  (finish-output)
  (let ((*read-eval* nil))
    (read)))

(defun leap-year-p (y)
  ; your implementation here
  ; return a truth value
  )

(defun check-leap-year ()
  (print (if (leap-year-p (prompt-for-year))
             "yes"
           "no")))

(check-leap-year)

【讨论】:

    【解决方案2】:

    在 lisp 语言中发生的频率,问题在于缺少(或多余的)括号。

    在您的情况下,函数定义中有多个括号问题,应该是:

    (defun leap-year (y)
      (if (and (= 0 (mod y 400)) (= 0(mod y 4)))
          (print "Is a leap year")
          (print "Is not")))
    

    在使用这些语言进行编程时,良好的表达式对齐规则和良好的程序编辑器(例如 Emacs)实际上非常重要(我会说“必不可少”)。

    请注意,如果您在 REPL 中使用该函数,则可以省略 print:

    (defun leap-year (y)
      (if (and (= 0 (mod y 400)) (= 0(mod y 4)))
          "Is a leap year"
          "Is not"))
    

    最后,请注意闰年检查是incorrect。正确的定义可能如下:

    (defun leap-year (y)
      (cond ((/= 0 (mod y 4)) "no")
            ((/= 0 (mod y 100)) "yes")
            ((/= 0 (mod y 400)) "no")
            (t "yes")))
    

    或者,使用if

    (defun leap-year (y)
      (if (or (and (zerop (mod y 4))
                   (not (zerop (mod y 100))))
              (zerop (mod y 400)))
          "yes"
          "no"))
    

    【讨论】:

    • 我正在使用命令提示符和记事本。我尝试运行您的代码,但没有显示输出。我不知道为什么。
    • 在命令提示符下你应该保留print
    猜你喜欢
    • 2014-01-11
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 2011-02-06
    • 2020-04-22
    • 2010-11-29
    相关资源
    最近更新 更多