我制作了这个程序来计算零钱和剩余的零钱。它的设置方式是获取找零金额,例如 495,然后将其转换为美元 4.95。现在我想去掉 .95 并保留 4,我该怎么做才能不四舍五入到 5?谢谢!
def main():
pennies = int(input("Enter pennies : "))
nickels = int(input("Enter nickels : "))
dimes = int(input("Enter dimes : "))
quarters = int(input("Enter quarters : "))
computeValue(pennies, nickels, dimes, quarters)
def computeValue(p,n,d,q):
print("You entered : ")
print("\tPennies : " , p)
print("\tNickels : " , n)
print("\tDimes : " , d)
print("\tQuarters : " , q)
totalCents = p + n*5 + d*10 + q*25
totalDollars = totalCents / 100
totalDollarsTrunc = int(format(totalDollars, '.0f'))
totalPennies = totalCents - (totalDollarsTrunc * 100)
print("Amount of Change = ", totalDollarsTrunc, "dollars and ", totalPennies ,"cents.")
if totalCents < 100:
print("Amount not = to $1")
elif totalCents == 100:
print("You have exactly $1.")
elif totalCents >100:
print("Amount not = to $1")
else:
print("Error")
请您参考如下方法:
在 Python 中,int() 在从 float 转换时截断:
>>> int(4.95)
4
也就是说,你可以重写
totalDollars = totalCents / 100
totalDollarsTrunc = int(format(totalDollars, '.0f'))
totalPennies = totalCents - (totalDollarsTrunc * 100)
使用 divmod 函数:
totalDollars, totalPennies = divmod(totalCents, 100)
