gpt4 book ai didi

coding-style - 使用 Scheme 代码求解二次方程?

转载 作者:行者123 更新时间:2023-12-01 09:40:31 24 4
gpt4 key购买 nike

我编写了这个方案代码来计算二次方程 ax2 + bx + c = 0

的一个解
(define (solve-quadratic-equation a b c) (define disc (sqrt (- (* b b) (* 4.0 a c)))) (/ (+ (- b) disc) (* 2.0 a)))

但是,有人告诉我,这个过程很难理解。为什么?

这个过程的清理版本会是什么样子?请告诉我为什么新程序更容易理解。

谢谢

最佳答案

嗯,一个原因是它都在一条线上。您可以使用称为 pretty-printing 的方法使其更具可读性,将其分成多行并使用空格:

(define (solve-quadratic-equation a b c)
(define disc (sqrt (- (* b b)
(* 4.0 a c))))
(/ (+ (- b) disc)
(* 2.0 a)))

这样你可以更清楚地看到表达式的结构。

这是来自 SICP 的引述:

There is no limit (in principle) to the depth of such nesting and to the overall complexity of the expressions that the Lisp interpreter can evaluate. It is we humans who get confused by still relatively simple expressions such as

(+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6))

which the interpreter would readily evaluate to be 57. We can help ourselves by writing such an expression in the form

(+ (* 3
(+ (* 2 4)
(+ 3 5)))
(+ (- 10 7)
6))

following a formatting convention known as pretty-printing, in which each long combination is written so that the operands are aligned vertically. The resulting indentations display clearly the structure of the expression.

关于coding-style - 使用 Scheme 代码求解二次方程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/249348/

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