首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有and运算符的If条件

带有and运算符的If条件
EN

Stack Overflow用户
提问于 2021-02-03 14:29:54
回答 2查看 91关注 0票数 0

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

代码语言:javascript
复制
(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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-03 19:26:48

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

代码语言:javascript
复制
(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"))

或者,不在顶层使用函数调用和全局变量也是一个好主意。编写所有内容的过程/函数。这样你的代码就会自动变得更加模块化,可测试性和可重用性更强。

代码语言:javascript
复制
(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)
票数 3
EN

Stack Overflow用户

发布于 2021-02-03 15:42:37

在lisp语言中,问题出在缺少(或多余)括号中。

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

代码语言:javascript
复制
(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

代码语言:javascript
复制
(defun leap-year (y)
  (if (and (= 0 (mod y 400)) (= 0(mod y 4)))
      "Is a leap year"
      "Is not"))

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

代码语言:javascript
复制
(defun leap-year (y)
  (cond ((/= 0 (mod y 4)) "no")
        ((/= 0 (mod y 100)) "yes")
        ((/= 0 (mod y 400)) "no")
        (t "yes")))

或者,使用if

代码语言:javascript
复制
(defun leap-year (y)
  (if (or (and (zerop (mod y 4))
               (not (zerop (mod y 100))))
          (zerop (mod y 400)))
      "yes"
      "no"))
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66022347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档