我计算小费的程序有什么问题?

2024-09-29 23:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的初学者,我想知道我设置的这个计算tips的程序有什么问题

total = input("What is the bill total? ")

tperc = input("Would you like to give a 15% or 20% tip? ")

tip15 = total * .15
tip20 = total * .20

if tperc == "15":
    print("\nThat would be a $" + tip15 + "tip.")

if tperc == "15%":
    print("\nThat would be a $" + tip15 + "tip.")

if tperc == "20":
    print("\nThat would be a $" + tip20 + "tip.")

if tperc == "20%":
    print("\nThat would be a $" + tip20 + "tip.")

input("\nPress enter to exit.")

谢谢你的帮助


Tags: to程序inputifbetotalprint初学者
1条回答
网友
1楼 · 发布于 2024-09-29 23:26:59
total = input("What is the bill total? ")
#...
tip15 = total * .15

在python3.X中,input返回一个字符串。不能将字符串与浮点数相乘。你知道吗

在做任何算术之前把total转换成一个数字。你知道吗

total = float(input("What is the bill total? "))

或者,在理想情况下,使用十进制类型进行货币计算,因为浮点运算往往是not perfectly accurate。你知道吗

from decimal import Decimal
total = Decimal(input("What is the bill total? "))
#...
tip15 = total * Decimal("0.15")

print("\nThat would be a $" + tip15 + "tip.")

这也是一个问题,因为不能将字符串和浮点/十进制连接起来。转换为字符串或使用字符串格式。后者可能更可取,因为您可以四舍五入到小数点后两位。你知道吗

print("\nThat would be a $" + str(tip15) + " tip.")
#or
print("\nThat would be a ${:.2f} tip.".format(tip15))

相关问题 更多 >

    热门问题