Python 截断整数而不舍入?

Python 截断整数而不舍入?,python,floating-point,python-3.x,truncate,Python,Floating Point,Python 3.x,Truncate,我做了一个程序,需要零钱,并计算出有多少完整的美元,以及剩余的零钱。它的设置方式是,取零钱的数量,例如495,然后将其转换为美元,4.95。现在我想去掉.95,留下4,如果不把它四舍五入,我怎么做?谢谢 def main(): pennies = int(input("Enter pennies : ")) nickels = int(input("Enter nickels : ")) dimes = int(input("Enter dimes : ")) quarters = int(in

我做了一个程序,需要零钱,并计算出有多少完整的美元,以及剩余的零钱。它的设置方式是,取零钱的数量,例如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")
def main():
便士=整数(输入(“输入便士:”)
镍币=int(输入(“输入镍币:”)
dimes=int(输入(“输入dimes:”)
季度=整数(输入(“输入季度:”)
计算值(便士、镍币、一角硬币、四分之一硬币)
def计算值(p、n、d、q):
打印(“您输入:”)
打印(“\t字体:”,p)
打印(“\t图标:”,n)
打印(“\t时间:”,d)
打印(“\t参数:”,q)
总计分=p+n*5+d*10+q*25
总计美元=总计美分/100
totalDollarsTrunc=int(格式为totalDollars,.0f'))
totalPennies=totalCents-(totalDollarsTrunc*100)
打印(“变更金额=”,totalDollarsTrunc,“美元和”,totalPennies,“美分”)
如果总分<100:
打印(“金额不等于1美元”)
elif totalCents==100:
打印(“您正好有1美元。”)
elif totalCents>100:
打印(“金额不等于1美元”)
其他:
打印(“错误”)
在Python中,从
浮点值转换时,
int()
会截断:

>>> int(4.95)
4
也就是说,你可以重写

totalDollars = totalCents / 100
totalDollarsTrunc = int(format(totalDollars, '.0f'))
totalPennies = totalCents - (totalDollarsTrunc * 100)
使用
divmod
功能:

totalDollars, totalPennies = divmod(totalCents, 100)
在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)

您可能想使用
math.ceil
math.floor
按您想要的方向取整。

您可能想使用
math.ceil
math.floor
按您想要的方向取整。

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

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

totalPennies=totalCents%100totalPennies=totalCents%100