我通过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 ...)

我的错误是很明显的东西相当愚蠢,但我是新来的计划,所以我不能找到它。 如果任何人有任何文体技巧,我会很感激这一点。谢谢!

有帮助吗?

解决方案

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

(product + 4 5)

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

(product-iter 1 1) should be (product-iter lo 1)

其他提示

在该呼叫中的函数product-iterproduct,它会做 (* 1 (factor 1))右在第一次迭代,这将评价为0,因为(factor 1)为0。因此,总的产品将是0以及

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top