Pro*_*XYZ 1 python floating-point truncate python-3.x
我做了这个程序,需要改变,并计算出多少全部美元和剩余的变化.它的设置方式,它需要更改量,例如495,然后将其转换为美元,4.95.现在我想切断.95然后离开4,如果没有它,我怎么做呢?谢谢!
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")
Run Code Online (Sandbox Code Playgroud)
在Python中,int()从float以下转换时截断:
>>> int(4.95)
4
Run Code Online (Sandbox Code Playgroud)
也就是说,你可以改写
totalDollars = totalCents / 100
totalDollarsTrunc = int(format(totalDollars, '.0f'))
totalPennies = totalCents - (totalDollarsTrunc * 100)
Run Code Online (Sandbox Code Playgroud)
使用divmod功能:
totalDollars, totalPennies = divmod(totalCents, 100)
Run Code Online (Sandbox Code Playgroud)