1

我没有在练习 21 中遵循以下部分,我想是因为我的数学很弱。

# A puzzle for the extra credit, type it in anyway.

print "Here is a puzzle."

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "That becomes: ", what, "Can you do it by hand?"

描述:

剧本的最后是一个谜题。我正在获取一个函数的返回值并将其用作另一个函数的参数。我在一个链中这样做,这样我就可以使用这些函数创建一个公式。它看起来很奇怪,但是如果你运行脚本你可以看到结果。您应该做的是尝试找出可以重新创建同一组操作的正常公式。

我的问题是什么是正常的公式,你是怎么计算出来的?

4

2 回答 2

4

您的代码行:

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

翻译为:

age + (height - (weight * (iq / 2)))

由于操作顺序,可以简化为:

age + height - weight * iq / 2

或英文:

Age plus Height subtract Weight times half of IQ

我解决它的方法是将语句扩展一点,以便更容易阅读:

第1步:

add(
    age, subtract(
        height, multiply(
            weight, divide(
                iq, 2
            )
        )
    )
)

然后从最里面的语句开始翻译每个语句:

第2步:

add(
    age, subtract(
        height, multiply(
            weight, (iq / 2)
        )
    )
)

第 3 步:

add(
    age, subtract(
        height, (weight * (iq / 2))
    )
)

第4步:

add(
    age, (height - (weight * (iq / 2)))
)

第 5 步:

age + (height - (weight * (iq / 2)))

编辑:

您需要对以下内容有基本的了解:

multiply(x, y) is equivalent to x * y
add(x, y) is equivalent to x + y
subtract(x, y) is equivalent to x - y
divide(x, y) is equivalent to x / y

然后您还需要了解这些可以组合:

multiply(x, add(y, z)) is equivalent to multiply(x, (y + z)), and  x * (y + z)

我用括号(y + z)表示应该首先计算它,因为在嵌入式函数中总是首先计算内部值。

于 2013-11-04T06:07:25.180 回答
1

“正常公式”是:年龄+(身高-(体重*(iq / 2)))

至于为什么,从你的代码开始:

add(age, subtract(height, multiply(weight, divide(iq, 2))))

这段代码将divide(iq, 2)首先执行,给我们 (iq/2)。为了形象化,我将用它的“正常”结果替换函数:

add(age, subtract(height, multiply(weight, (iq/2))))

有了这个值,multiply(weight, (iq/2))就可以计算出来了。所以weightiq/2相乘—— weight*(iq/2)。同样,用“正常”结果替换函数:

add(age, subtract(height, (weight*(iq/2)))

现在计算 `subtract(height, (weight*(iq/2))),从第一个参数中减去第二个参数:

add(age, (height - (weight * (iq/2))))

最后,add()被评估并添加age到等式的其余部分,因此您的最终“正常”结果是:

age + height - (weight * iq/2)
于 2013-11-04T06:23:56.680 回答