我自己通过 SICP 工作,所以我没有教练可以询问这个问题。此代码应该近似于 pi,但始终返回零。
(define (approx-pi acc)
(define (factors a)
(define basic-num
(if (= (mod a 2) 0)
(/ a 2)
(/ (- a 1) 2)))
(if (= (mod basic-num 2) 0)
basic-num
(/ 1 basic-num)))
(* 4 (product factors 5 (* 2 acc))))
以下是此代码中引用的 mod 和产品过程。这些似乎不是问题,但我会包括它们以防万一。
(define (product func lo hi)
(define (product-iter i result)
(if (> i hi)
result
(product-iter (+ 1 i) (* result (func i)))))
(product-iter 1 1))
(define (mod a b)
(if (< (- a b) 0)
a
(mod (- a b) b)))
整个事情是公式的实现:
pi / 4 = (2 * 4 * 4 * 6 ...) / (3 * 3 * 5 * 5 ...)
我的错误显然很愚蠢,但我是Scheme的新手,所以我找不到它。如果有人有任何风格提示,我也会非常感激。谢谢!