如果条件与运算符

If condition with and operator

如何将 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 语言中发生的频率,问题在于缺少(或多余的)括号。

在你的例子中,函数定义中有多个括号问题,应该是:

(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"))

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

(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"))

或者,最好不要在顶层使用函数调用和全局变量。为所有内容写 procedures/functions。这样您的代码就会自动变得更加模块化、可测试和可重用。

(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)