大多数小费计算器应用程序只收取餐费的固定百分比。因此,例如,如果您的餐费为$ 23.45,则可以保留15%的小费= $ 3.52,或更慷慨的20%的小费= $ 4.69。
方便信用卡用户使用。但是,如果您不愿留下现金小费,则情况并非如此,在这种情况下,这些零头钱占了很大一部分。因此,让我们修改一下想法,以使现金用户更加方便。
您的作业
编写尽可能少的字节作为输入的程序或函数:
- 一顿饭的价格
- 最小提示百分比
- 最大小费百分比
并输出在[price * min_percentage / 100,price * max_percentage / 100]范围内的任何小费金额,以使所需的纸币/钞票和硬币数量最小化。
假设美国的货币面额为1¢,5¢,10¢,25¢,$ 1,$ 5,$ 10,$ 20,$ 50和$ 100。
例
这是Python中的非示例程序:
import math
import sys
# Do the math in cents so we can use integer arithmetic
DENOMINATIONS = [10000, 5000, 2000, 1000, 500, 100, 25, 10, 5, 1]
def count_bills_and_coins(amount_cents):
# Use the Greedy method, which works on this set of denominations.
result = 0
for denomination in DENOMINATIONS:
num_coins, amount_cents = divmod(amount_cents, denomination)
result += num_coins
return result
def optimize_tip(meal_price, min_tip_percent, max_tip_percent):
min_tip_cents = int(math.ceil(meal_price * min_tip_percent))
max_tip_cents = int(math.floor(meal_price * max_tip_percent))
best_tip_cents = None
best_coins = float('inf')
for tip_cents in range(min_tip_cents, max_tip_cents + 1):
num_coins = count_bills_and_coins(tip_cents)
if num_coins < best_coins:
best_tip_cents = tip_cents
best_coins = num_coins
return best_tip_cents / 100.0
# Get inputs from command-line
meal_price = float(sys.argv[1])
min_tip_percent = float(sys.argv[2])
max_tip_percent = float(sys.argv[3])
print('{:.2f}'.format(optimize_tip(meal_price, min_tip_percent, max_tip_percent)))
一些示例输入和输出:
~$ python tipcalc.py 23.45 15 20
4.00
~$ python tipcalc.py 23.45 15 17
3.55
~$ python tipcalc.py 59.99 15 25
10.00
~$ python tipcalc.py 8.00 13 20
1.05
a program that takes as input (stdin, command-line arguments, or GUI input box, whichever is most convenient in your language)是否打算覆盖我们的输入和输出默认值?就是说,例如,允许使用三个数字并返回结果的函数?
3.51并且3.75也是测试用例的有效输出23.45 15 17?他们使用相同数量的硬币,并且也在范围内。