Python 货币计算脚本的问题

Python 货币计算脚本的问题,python,python-3.x,Python,Python 3.x,我的点钞脚本有问题。 它工作正常,但我需要用两种方式格式化输出,但我不能使用任何字符串函数,包括format,但我想使用math lib floor ceil函数 import math coins1 = int(input("Quantity of 1 cent coins ? ")) * 0.01 coins2 = int(input("Quantity of 2 cent coins ? ")) * 0.02 coins3 = int(input("Quantity of 5 cen

我的点钞脚本有问题。 它工作正常,但我需要用两种方式格式化输出,但我不能使用任何字符串函数,包括format,但我想使用math lib floor ceil函数

import math

coins1 = int(input("Quantity of 1 cent coins ? ")) * 0.01

coins2 = int(input("Quantity of 2 cent coins ? ")) * 0.02

coins3 = int(input("Quantity of 5 cent coins ? ")) * 0.05

coins4 = int(input("Quantity of 10 cent coins ? ")) * 0.10

coins5 = int(input("Quantity of 20 cent coins ? ")) * 0.20

coins6 = int(input("Quantity of 50 cent coins ? ")) * 0.50

coins7 = int(input("Quantity of 1 euro coins ? ")) * 1

coins8 = int(input("Quantity of 2 euro coins ? ")) * 2

bills1 = int(input("Quantity of 5 euro bills ? ")) * 5

bills2 = int(input("Quantity of 10 euro bills ? ")) * 10

bills3 = int(input("Quantity of 20 euro bills ? ")) * 20

bills4 = int(input("Quantity of 50 euro bills ? ")) * 50



total = coins1 + coins2 + coins3 + coins4 + coins5 + coins6 + coins7 + coins8 + coins1 + bills2 + bills3 + bills4


print("You've got", total, "euro and",)
我当前的输出是:

You've got 32792039464.8 euro and
我的目标是:

You've got 32792039464 euro and 80 cents.
$32.792.39.464,80
只需使用
int()
获取整数部分,使用模
%
获取小数部分:

print("You've got", int(total), "euro and", total % 1, "cents.")

您很快就会注意到一个关于浮点数的经典问题:)

您首先需要将总数%1乘以100,以得到美分的值

cents = math.ceil(total%1 * 100) ## for 32792039464.8 cents will be 0.8. times 100 is 80.
total = math.floor(total - cents/100) ## round the number down

print("You've got", total, "euro and ", cents, " cents.")
您还可以使用以下选项:

cents = round(total%1 * 100) ## for 32792039464.8 cents will be 0.8. times 100 is 80 cents.
total = round(total - cents/100) ## round the total down. 32792039464.8 to 32792039464

print("You've got", total, "euro and ", cents, " cents")

math.floor(total)
能给你带来什么?请不要编辑你的问题来包含答案的改进。如果你觉得你需要问更多的问题,那就去问一个新问题。我把你的问题还原成原来的形式,这样现在的答案就不会过时了。对不起,我的错。我是新来的,不知道规则。不要用浮动来表示钱。使用整数美分,并使用
divmod
获取欧元和美分的数字,以便显示。仅供参考:。宁可把每件事都记在分上。这将使您的生活更轻松,您只需使用模运算符
%
和。同时避免使用诸如
var1
var2
var3
等名称,而应使用
cent1=int(input())
cent2=int(input())*2
cent5=int(intput())*5
euro1=int(input())*100
,等等,在这种情况下,使用有意义的数字,而不仅仅是
硬币
+
计数器
“一个经典的浮点数问题”。也许你应该建议如何克服这个问题
round(x,2)
应该可以做到。是的,我马上就注意到了;P@NChauhan这是故意留给读者的练习:)
cents=math.ceil(总计%1*100)
是错误的。如果
total=1.23001
,这可能是因为您在浮点数,那么
cents
将是
24
,而不是
23
(在这种情况下是正确的)。无论如何,不要用浮动来赚钱。因为跳跃间隔在一美分之内,所以总的浮动不能是1.23001。这意味着总计将从1.23增加到1.24。浮动不是这样工作的:)参见例如关于浮动。另外,请参见中的示例,该示例还链接到。这就是为什么你不使用浮动来赚钱。