截断整数而不舍入吗?

2024-06-23 19:10:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个程序,它接受零钱,计算出多少美元,以及剩余的零钱。它的设置方式是,取变化量,例如495,然后转换成美元,4.95。现在我想把0.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")

Tags: youinputdefamountintprintenter零钱
3条回答

函数int()就可以做到这一点

在Python中,int()在从float转换时截断:

>>> int(4.95)
4

也就是说,你可以重写

^{pr2}$

使用divmod函数:

totalDollars, totalPennies = divmod(totalCents, 100)

您可能需要使用math.ceilmath.floor来向您想要的方向舍入。在

相关问题 更多 >

    热门问题