แอพเครื่องคิดเลขทิปส่วนใหญ่คิดราคาอาหารเพียงเล็กน้อย ตัวอย่างเช่นหากมื้ออาหารของคุณคือ 23.45 เหรียญคุณสามารถฝาก 15% เคล็ดลับ = $ 3.52 หรืออีก 20% เคล็ดลับ = $ 4.69
สะดวกเพียงพอสำหรับผู้ใช้บัตรเครดิต แต่ไม่เป็นเช่นนั้นหากคุณต้องการฝากเคล็ดลับเงินสดซึ่งในกรณีนี้จำนวนเงินที่ได้จากการจับคู่ลูกบอลเหล่านี้จะเข้าทาง ดังนั้นขอแก้ไขความคิดให้สะดวกยิ่งขึ้นสำหรับผู้ใช้เงินสด
การมอบหมายของคุณ
เขียนโปรแกรมหรือฟังก์ชั่นที่รับเป็นอินพุต: ในไม่กี่ไบต์
- ราคาของอาหาร
- เปอร์เซ็นต์เคล็ดลับขั้นต่ำ
- เปอร์เซ็นต์เคล็ดลับสูงสุด
และส่งออกจำนวนเงินทิปใด ๆ ในช่วง [ราคา * min_percentage / 100, ราคา * 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หรือไม่ พวกเขาใช้เหรียญจำนวนเท่ากันและอยู่ในขอบเขต