点钞票问题

2024-04-29 07:36:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在数钱的剧本上有点问题。 它工作得很好,但我需要两种方式格式化输出,但我不能使用任何字符串函数,包括格式,但我想使用数学库地板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

Tags: andof函数youinputvecentquantity
2条回答

您首先需要将总数%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")

只需使用int()获得整数部分,使用模%获得小数部分:

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

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

相关问题 更多 >