方案:平方根的递归

时间:2014-01-22 11:20:20

标签: scheme

(define average (lambda (x y)(/ (+ x y) 2)))
(define improve (lambda (guess X)(average guess (/ X guess))))
(define close-enuf? (lambda(guess X) (<(abs (- (* guess guess) X))0.1)))
(define loop (lambda (guess X)(if close-enuf? guess X ) guess (loop (improve guess X) X)))
(loop 3 2)

当我尝试运行程序时,它没有给出任何输出。我该如何解决?

1 个答案:

答案 0 :(得分:3)

我建议您使用更好的缩进样式编写代码,因为它会使错误更明显。

(define average 
  (lambda (x y)(/ (+ x y) 2)))

(define improve 
  (lambda (guess X)(average guess (/ X guess))))

(define close-enuf?
  (lambda(guess X) 
    (< (abs (- (* guess guess) X)) 0.5)))

(define loop 
  (lambda (guess X)
    (if close-enuf? guess X) ;; see the error here? (if (close-enuf? guess X)
        guess (loop (improve guess X) X))) ;need another bracket here

我得到了答案1 21145/50952。