学习Python艰难的方式,Ex21,EC3

010*_*amt 0 python

Ex21,额外学分3:一旦你完成拼图的公式,进入那里,看看修改功能的各个部分会发生什么.尝试有意改变它以产生另一个价值.

我的代码:

def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b


print "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)



print "Here is a puzzle."


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

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



print "That becomes: ", what, "Can you do it by hand?"
Run Code Online (Sandbox Code Playgroud)

我为这个练习写的新公式是注释#new公式.在编写并运行它之后,我注意到发生了一些奇怪的事情:分区时代/ 2中的浮点被忽略.

问题:为什么Python忽略了age/2中的浮点(也是进一步的操作),如何让它忽略它呢?

nin*_*cko 5

如果你没有使用python3,你必须开始你的主要python文件

from __future__ import division
Run Code Online (Sandbox Code Playgroud)

制作1/2 == 0.5.否则1/2 == 0(整数除法,基本上四舍五入).

1//2如果由于某种原因你真的想要它,你总是可以使用访问整数除法.