您好我正在阅读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
这是什么意思以及如何解决问题?
答案 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))