1

我制作了这个程序,它需要零钱并计算出多少整美元和剩余的零钱。它的设置方式是取零钱,例如 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")
4

3 回答 3

8

在 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)
于 2012-10-26T01:27:38.950 回答
2

您可能想要使用math.ceilmath.floor向您希望的方向进行四舍五入。

于 2012-10-26T01:27:54.803 回答
2

函数int()将做到这一点

于 2012-10-26T01:28:11.810 回答