定义一个过程,该过程将三个数字作为参数,并返回两个较大数字的平方和



我很难弄清楚如何整理出 2 个最大的数字并将它们返回到平方和程序中。我正在努力用 Scheme 的语法编写代码。我试图把它写得尽可能干净,我一直在脑海里和纸上转圈,试图这样做。这本书描述了"程序性"思维,我认为我在这方面遇到了麻烦。

本书提供了平方和和平方过程的代码。我会包括我的伪代码,但我严重迷失了。以下是本书提供的代码:

(define (square x) (* x x))
(define (sum-of-squares x y)
  (+ (square x) (square y)))

如何定义一个以三个数字作为参数并返回两个较大数字的平方和的过程?

如何定义一个以三个数字作为参数并返回两个较大数字的平方和的过程?

首先,您需要为该过程命名。让我们称之为sum-of-squares-two-largest.

(define (sum-of-squares-two-largest x y z)
   ...)

它可以利用 sum-of-squares 函数,但它需要首先从 x,y,z 中找到两个最大的数字。

一种方法是摆脱最小的数字。您可以定义一个帮助程序过程smallest? a b c通过执行 (and (<= a b) (<= a c)) 来检查 a 是否是 3 个数字中最小的一个。

(define (sum-of-squares-two-largest x y z)
   (if (smallest? x y z)
       (sum-of-squares y z)
       (if (smallest? y x z)
           ...]

编写min-of-three的代码。它的负片(如摄影)是你需要的:

(define (negative-min-of-three a b c)
   (if (<= a b)
       (if (<= a c)
           (..... b ... c .....)
           (..... a ... b .....))
       (if (<= 
   ..........

您可以完成代码,并对其进行重命名。时钟在滴答作响!

我创建了两种方法来暂时获得最大和中间的一种方法。

(define (largest x y z)
  (cond ((and (> x y) (> x z)) x)
        ((and (> y x) (> y z)) y)
        (else z))
)
(define (mid x y z)
  (cond ((and (> x y) (< x z)) x)
        ((and (> y x) (< y z)) y)
        (else z))
)
(define (square a)
  (* a a)
)
(define (sum-of-two-largest x y z)
  (+ (square (largest x y z)) (square (mid x y z)))
)
(sum-of-two-largest -12 -4 1)

困难的部分是,如果您正在阅读 SICP 书籍,请找到三者中第二大的数字。你可以观察到,如果我们让 c <a,那么:>

a = max(a, b) gives the largest of the two numbers
b = max(c, b) gives the largest of the two smaller numbers

但是我们如何在第二行上得到变量 b。碰巧 a 是两者中较小的一个吗?我们可以观察到:

b = min(a, b)

如果我们在第三行的 max 函数中用 min(a, b) 代替 b,我们得到:

b = max(c, min(a, b))

此策略在以下代码中实现,仅使用到目前为止书中介绍的构造:

(define (square x) (* x x))
(define (max a b) (if (> a b) a b))
(define (min a b) (if (< a b) a b))
(define (sum-of-squares-two-largest a b c)
   (+ (square (max a b)) (square (max c (min a b)))))
(sum-of-squares-two-largest 1 2 3)
(sum-of-squares-two-largest 1 2 1)

最新更新