Python提示计算器错误

2024-04-20 10:55:24 发布

您现在位置: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。我完全是个初学者。你知道吗


Tags: thetoyouforisascashcan
1条回答
网友
1楼 · 发布于 2024-04-20 10:55:24

In Python 2除法运算符/执行整数除法,如果分子和分母都是ints(在本例中是这样,因为您使用了input())。所以这次行动:

# if tip = 10
tip = 10/100

将返回0,因为两个值的类型都是int。你知道吗


由于需要浮点除法,因此可以从^{}模块导入division运算符:

from __future__ import division

tip = 10 / 100 # returns 0.1

或者,在实际除法之前,将类型inttip强制转换为float

tip = float(10) / 100 # returns 0.1

相关问题 更多 >