【问题标题】:Truncating ints without rounding?截断整数而不舍入?
【发布时间】:2012-10-26 01:26:04
【问题描述】:

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

【问题讨论】:

  • totalPennies = totalCents%100

标签: python floating-point python-3.x truncate


【解决方案1】:

在 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)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2011-01-26
        • 1970-01-01
        • 2011-12-27
        • 1970-01-01
        • 2017-01-29
        • 2013-03-20
        • 1970-01-01
        相关资源
        最近更新 更多