3

嗨,我正在阅读 SICP,我被困在练习 1.7 中:

这是我的代码:

(define (avg x y)
  (/ (+ x y) 2))

;;(avg 1 2)


(define (square x)
  (* x x))

;;(square 2)


(define (improve guess x)
  (avg guess (/ x guess)))

;;(improve 1 2)


(define (good-enough? x guess)
  (< (abs (- guess ((avg guess (/ x guess))))) 0.1))

(define (sqrt-iter guess x)
  (if (good-enough? guess x)
      guess
      (sqrt-iter (improve guess x)
                 x)))

(define (my-sqrt x)
  (sqrt-iter 1.0 x))

(my-sqrt 100)

DrRacket 给出了一个错误:

函数调用:在左括号后需要一个函数,但收到 50.005

这是什么意思以及如何解决这个问题?

4

1 回答 1

2

代码中有几个错误,包括放错位置的括号。对于初学者,good-enough?如练习 1.7 中定义的那样,应该如下所示:

(define (good-enough? guess-old guess-new)
  (< (/ (abs (- guess-old guess-new)) guess)
     (/ 0.001 guess)))

并且sqrt-iter,正如您在代码中所写的那样,将导致无限递归。试试这个:

(define (sqrt-iter guess-old guess-new x)
  (if (good-enough? guess-old guess-new)
      guess-new
      (sqrt-iter guess-new (improve guess-new x) x)))

(define (my-sqrt x)
  (sqrt-iter 0.0 1.0 x))
于 2013-09-12T02:13:12.763 回答