SICP书籍解决方案错误帮助,编号1.7

时间:2013-09-12 01:56:38

标签: lisp scheme sicp racket

您好我正在阅读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

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

1 个答案:

答案 0 :(得分:2)

代码中有一些错误,包括错误的括号。对于初学者,练习1.7定义的good-enough?应如下所示:

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