我正在用Python编写一个简单的程序。但我无法理解为什么它不存储Hcount,Scount和Fcount的值。此外,它没有正确显示税。任何帮助将不胜感激
while True:
print("MacDoogle's:")
print("1. Hamburger = $1.50")
print("2. Soda = $1.15")
print("3. Fries = $1.25")
print("4. Complete Order")
choice = int(input('Make a selection: '))
while choice < 1 or choice > 4:
choice = int(input('Enter a valid selection: '))
Hcount =0
Scount =0
Fcount =0
if choice > 0 and choice <4:
if choice == 1:
amount1=int(input("Enter number of Hamburgers: "))
Hcount += amount1
elif choice == 2:
amount2=int(input("Enter number of Sodas: "))
Scount += amount2
elif choice == 3:
amount3=int(input("Enter number of Fries: "))
Fcount += amount3
if choice == 4:
sub=int((Hcount * 1.50) + (Scount * 1.15) + (Fcount * 1.25))
tax=int(sub * 0.09)
total=int(sub + tax)
print('Number of Hamburgers:', format(Hcount, '3.0f'))
print('Number of Sodas:', format(Scount, '3.0f'))
print('Number of Fries:', format(Fcount, '3.0f'))
print('Subtotal:', format(sub, '3.2f'))
print('Tax:', format(tax, '3.2f'))
print('Total:', format(total, '3.2f'))
break
答案 0 :(得分:0)
这不是https://codereview.stackexchange.com/但是我有点无聊并想帮助你
if
,elif
或while
语句后应有4个缩进空格while
循环 if choice > 0 and choice < 4
可以重写为0 < choice < 4
您的if choice > 0 and choice < 4
是多余的。您可以删除此
while
循环是多余的 - 你根本不需要这个amount0
,amount1
和amount2
int()
- 这会从您的数字中删除小数位,从而导致您的税收从未计算过。格式化字符串时,如果要将其格式化为2位小数,可以使用'Subtotal: {:0.2f}'.format(sub)
hcount = 0
scount = 0
fcount = 0
while True:
print("MacDoogle's:")
print("1. Hamburger = $1.50")
print("2. Soda = $1.15")
print("3. Fries = $1.25")
print("4. Complete Order")
choice = int(input('Make a selection: '))
if choice == 1:
amount = int(input("Enter number of Hamburgers: "))
hcount += amount
elif choice == 2:
amount = int(input("Enter number of Sodas: "))
scount += amount
elif choice == 3:
amount = int(input("Enter number of Fries: "))
fcount += amount
elif choice == 4:
sub = (hcount * 1.50) + (scount * 1.15) + (fcount * 1.25)
tax = sub * 0.09
total = sub + tax
print('Number of Hamburgers: {0}'.format(hcount))
print('Number of Sodas: {0}'.format(scount))
print('Number of Fries: {0}'.format(fcount))
print('Subtotal: {:0.2f}'.format(sub))
print('Tax: {:0.2f}'.format(tax))
print('Total: {:0.2f}'.format(total))
break
答案 1 :(得分:0)
这是因为每次循环迭代时,Hcount,Scount,Fcount都被赋值为0。将Hcount =0
Scount =0
Fcount =0
放在while循环前面,它应该可以解决您的问题
答案 2 :(得分:0)
这个强制转换为int
会丢弃小数点右边的内容。考虑将所有内容存储在美分中,然后乘以100
sub_in_cents = (hcount * 150) + (scount * 115) + (fcount * 125)
tax_in_cents = int(sub * 0.09)
total_in_cents = sub_in_cents + tax_in_cents
total_in_dollars = total_in_cents*1./100