5

我自己通过 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的新手,所以我找不到它。如果有人有任何风格提示,我也会非常感激。谢谢!

4

2 回答 2

3

你的产品功能有一个微妙的缺陷:

(product + 4 5)

正确答案为 20 时返回 120。原因是

(product-iter 1 1) should be (product-iter lo 1)
于 2009-11-08T05:29:11.110 回答
0

product-iter在对函数的调用中product,它会 (* 1 (factor 1))在第一次迭代中正确执行,因为(factor 1)是 0,所以计算结果为 0。因此,总乘积也将为 0。

于 2009-11-08T05:27:07.273 回答