我的货币计数脚本出现问题。 它工作正常,但是我需要用两种方式格式化输出,但是我不能使用任何字符串函数,包括format,但是我想使用math lib floor ceil函数。
In [183]: c = {0: array([4., 5., 0 ]), 1: array([3, 4]), 2: array([1, 1.])}
In [185]: [np.allclose(a[k],c[k]) for k in a]
....
ValueError: operands could not be broadcast together with shapes (2,) (3,)
我当前的输出是:
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
答案 0 :(得分:1)
只需使用int()
即可得到整数部分,而取模%
即可得到小数部分:
print("You've got", int(total), "euro and", total % 1, "cents.")
您会很快发现经典的浮点数问题 :)
答案 1 :(得分:1)
首先,您需要将%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")