四舍五入到小数点后两位并在小费计算器中转换百分比

问题描述 投票:0回答:2

这些是该项目的参数:

  • 如果账单为 150.00 美元,则分给 5 人,并支付 12% 的小费。
  • 每人应支付(150.00 / 5) * 1.12 = 33.6
  • 将结果格式化为小数点后两位 = 33.60
bill = input("What is the total bill?")

# bill is 150.00

tip = input("What percentage tip would you like to give? 10, 12, or 15?")

# tip will be 12%

max_tip = float(tip) / 100

# split between 5 people
people = input("How many people to split the bill?")

max_split = int(bill) / int(people)
max_cost = int(max_split) * float(max_tip)

print(f"Each person should pay:{max_cost}")

这是我当前的输出:

What is the total bill?150
What percentage tip would you like to give? 10, 12, or 15?12
How many people to split the bill?5
Each person should pay:3.5999999999999996

我从之前的课程中知道你可以

round(number, 2)
,这应该意味着Python将小数点后两位四舍五入。

float(max_tip, 2)
是唯一对我有意义的地方,但我的输出是:

line 77, in <module>
    max_cost = int(max_split) * float(max_tip, 2)
TypeError: float expected at most 1 argument, got 2

Process finished with exit code 1

如何将小数点后两位四舍五入?

另外,如何将 12% 变成 1.12?

python
2个回答
1
投票

我不完全确定你想从这个问题中得到什么,但这里有一些对你的代码的修复。首先,您想知道如何舍入,您可以使用

round()
方法,其第一个参数是数字,第二个参数是您想要舍入到的位数。您还询问了将 0.12% 更改为 1.12 您愿意做的一切
(tip / 100) + 1
。我已将这些更改添加到下面的代码中:

bill = float(input("What is the total bill?"))
tip = int(input("What percentage tip would you like to give? 10, 12, or 15?"))
people = int(input("How many people to split the bill?"))

decimal_multiplier = tip / 100 + 1
max_split = bill / people
max_cost = round((max_split * decimal_multiplier), 2)

print(f"Each person should pay: {max_cost}")

-1
投票
print("Welcome to the tip calculator!")
bill = float(input("What was the total bill? $"))
tip = int(input("What percentage tip would you like to give? 10 12 15 "))
people = int(input("How many people to split the bill? "))
amount = round((bill*(1+tip/100)/people), 2)
print(f"Each person should pay: ${amount}")
© www.soinside.com 2019 - 2024. All rights reserved.