gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:01:00 25 4
gpt4 key购买 nike

我无法弄清楚如何找出 2 个最大的数字并将它们返回到平方和过程中。我正在努力用 Scheme 的语法写出代码。我试图尽可能干净地写它,并且我一直在脑海中和纸上绕圈子试图这样做。这本书描述了“按程序”思考,我认为我在这方面遇到了麻烦。

本书提供了平方和和平方过程的代码。我会包括我的伪代码,但我迷路了。这是本书提供的代码:

(define (square x) (* x x))

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

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

最佳答案

How to define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers?

首先,您需要为过程命名。我们称它为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)
...]

关于sorting - 定义一个过程,该过程将三个数字作为参数并返回两个较大数字的平方和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com