Python现金收银程序输入浮点价格自动取整问题求助
解决输入小数价格被取整的问题
你的代码里导致小数被取整的原因很明确,两处关键错误:
- 输入价格时的强制转int:
int(float(input(...)))这行先把输入转成float,接着用int()直接截断了小数部分,比如3.20转成float是3.2,int之后就变成3了。 - 类中总价的初始类型错误:
self.price = int(float(0.00))把总价初始化成了整数类型,后续累加自然也都是整数运算。 - 额外提个笔误:
__init__里的mself.items应该是self.items,不然会触发属性错误。
修改后的完整代码如下:
import locale class CashRegister: def __init__(self): self.items = 0 self.price = 0.0 # 直接初始化为float类型 def addItems(self, price): # 跟踪购物车商品总数和总价 self.price += price self.items += 1 print(self.price) def getTotal(self): # 返回总价 return self.price def getCount(self): # 返回商品数量 return self.items def clearCart(self): # 清空购物车 self.items = 0 self.price = 0.0 def main(): user_name = input('What is your name?\n') # 欢迎用户 print("Hello", user_name) locale.setlocale(locale.LC_ALL, 'en_US') register = CashRegister() # 实例化收银对象,变量名别和用户名重复,避免混淆 while True: line = input("Would you like to add another food item to your cart? Choose y or n \n") if line == "y": price = float(input("please input the price of the item\n")) # 直接转成float,保留小数 print(price) register.addItems(price) # 添加商品到购物车 elif line == "n": print("Your total checkout price:", locale.currency(register.getTotal())) print("Your total item count", register.getCount()) register.clearCart() # 清空购物车 break else: print("Error") if __name__ == '__main__': main()
修改后测试:输入3.20时,price会被正确保留为3.2,累加后的总价也会保留小数位,locale.currency会自动格式化为$3.20这样的货币格式,完全符合需求。
内容的提问来源于stack exchange,提问作者Bree Parker
相关产品推荐
相关产品推荐

