Scheme——防止程序被0除时崩溃

Scheme - prevent program from crashing when dividing by 0

我的程序从文件中中断函数,比如

   (   10          (print "+1/+0    = " (/ (+ 1) (+ 0))))
   (   11          (print "-1/+0    = " (/ (- 1) (+ 0))))

除了我的程序崩溃

/: division by zero
     context...:

我知道我可以将 0.0 添加到 0 中,但是还有其他更简单的方法吗?

好吧,你可以处理错误并显示一条消息……

(with-handlers ([exn:fail? (lambda (exn)
                             (printf "+1/+0    = +inf.0"))])
  (printf "+1/+0    = ~s" (/ (+ 1) (+ 0))))

…或者您可以转换每个数字以确保使用浮点除法:

(printf "+1/+0    = ~s"
        (/ (exact->inexact (+ 1)) (exact->inexact (+ 0))))

但何必呢?如果您知道整数除以零并且使您的程序崩溃,那么请确保直接使用浮点除法输入文件:

(printf "+1/+0    = ~s" (/ (+ 1.0) (+ 0.0)))

上述任何选项都将打印相同的结果:

+1/+0    = +inf.0