Python提示计算器错误

时间:2015-10-27 18:49:28

标签: python

以下代码应该可以顺利运行,但由于某种原因终端告诉我它存在问题。我的问题在底部。

print 'Welcome to Cash Calculator!'

cash = input('How much was the original price of the services or goods you paid for, excluding vat?')
tip = input('How much more, as a percentage, would you like to give as a tip?')

tip = tip/100

print tip

vat = 1.2

cash_vat = cash * vat

can = (cash_vat + ((tip/100) * cash_vat))

can = cash_vat + tip * cash_vat

print """
Thank you for your co-operation.
The price excluding the tip is %r,
and the total price is %d.
"""  % (cash_vat, can)

当上面的代码运行时终端发出:

Welcome to Cash Calculator!
How much was the original price of the services or goods you paid for, excluding vat?100
How much more, as a percentage, would you like to give as a tip?10
0

Thank you for your co-operation.
The price excluding the tip is 120.0,
and the total price is 120.

似乎有什么问题?它一直认为提示是0.我是一个完全的初学者。

1 个答案:

答案 0 :(得分:2)

如果分子和分母都是/(在这种情况下它们是,因为你使用了ints),

In Python 2除法运算符input()执行整数除法。所以操作:

# if tip = 10
tip = 10/100

将返回0,因为这两个值都是int类型。

由于您需要浮点除法,您可以从__future__模块导入division运算符:

from __future__ import division

tip = 10 / 100 # returns 0.1

或者,或者,在实际分割之前,将tip类型int投射到float

tip = float(10) / 100 # returns 0.1