掌握有特定要求的小费计算器的逻辑挑战(python)

2024-05-12 23:41:40 发布

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

我正在为学校编写一个包含以下参数的程序:

写一个程序,计算XXX%的小费和6%的餐费税。用户将输入膳食价格,程序将计算小费、税和总额。总数是餐费加小费加上税金。然后,程序将显示小费、税金和总额的值。在

餐厅现在想改变计划,这样小费的百分比是基于餐费的。新数额如下:

Meal Price Range       Tip Percent
.01 to 5.99            10%
6 to 12.00             13%
12.01 to 17.00         16%
17.01 to 25.00         19%
25.01 and more         22%

以下是我目前为止的代码:

def main():

^{pr2}$

从这里开始,我没有成功地接受用户输入并计算user*tax+user=total。这应该是我的计算,但我如何实现它。这是在python3.6idle上运行的。在


Tags: to用户程序参数价格餐厅学校计划
3条回答

您可以定义一个基于餐价设置的tip变量。在

user = float(input("Please input the cost of the meal "))
tip = 0 # we'll overwrite this
if user > .01 and user < 5.99:
  tip = 0.1
elif user > 5.99 and user < 12:
  tip = 0.13
# etc, until...
else:
    # at this point user should be >= 25.01
    tip = 0.22

然后找到实际的小费“价格”,并将其加到总计中:

^{pr2}$

您需要:

import numpy as np
def price(x):
    if x<=0: return 0
    tax = 0.06
    a = np.array([0.01, 6, 12.01, 17.01, 25.01])
    b = np.array([10, 13, 16, 19, 22])/100
    tip = dict(zip(a, b)).get(a[(x>=a).sum()-1] , 0)
    return round(x * (1 + tax ) + tip,3)   

对于价格5,我们有5+(5*0.06) +0.1 = 5.4,价格=17,然后是{},对于{}: 现在调用我们的price函数:

^{pr2}$

在这一行之后,您要执行您的逻辑:

if user < .01 and user > 5.99:

(我假设这应该是0.01美元到5.99美元之间的总额) 一个例子如下:

if user > .01 and user <= 5.99:
    print("Total is: " + str((user*tax)*a))
elif user > 5.99 and user <= 12.00:
    print("Total is: " + str((user*tax)*b))

等等

相关问题 更多 >