如何将以毫米为单位的数字转换成表示米、厘米和毫米的数字?

2024-05-23 22:38:38 发布

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

我的代码尝试将一个数字转换为例如XY厘米和Z毫米。我的代码可以正确地处理没有零的数字,如5782,但当涉及到带零的数字时,它将无法正常工作

这是我的代码:

a = 2200
b = a / 1000
print(float(b))
b = str(float(b)).split(".") 
first = b[0] 
print(first,b[1])

c = (float(b[1])/10)
print(c)
c = str(c).split(".")
print(c)

second = (c[0])
third = (c[1])



print("%s Meter %s centimeter %s milimeter"%(first,second,third))
 

结果必须像2米20厘米0毫米但是它给了我2米0厘米2毫米

我怎么才能解决这些家伙


Tags: 代码数字floatfirstsplitmeterprintsecond
2条回答

真的,真的,真的不应该使用intstr转换和split方法来删除小数

所以,我看到你们在做的是毫米到米,厘米,毫米。我要做的是使用math.floor删除小数点-

import math
a = 2200
meters = math.floor(a / 1000)
centimeters = math.floor((a - meters * 1000) / 10)
millimeters = math.floor(a - meters * 1000 - centimeters * 10)
print(meters, centimeters, millimeters)

使用整数除法:

print( 27 // 4 ) # prints 6 because 6*4 = 24 and 7*4 is too big

用整数除法得到2200 mmmm(2)中的“满”米数,然后从mm值中减去2*1000,继续cm,剩下的是mm

mm = 2200        # startvalue in mm

m = mm // 1000   # how many full meters in mm?
mm -= m*1000     # reduce mm by amount of mm in full meters

cm = mm // 10    # how many full centimeter in mm?
mm -= cm*10      # reduce mm by amount of mm in full centimeters

print(f"{m} meter {cm} centimeter {mm} millimeter")

输出:

 2 meters 20 centimeter 0 millimeter

如果要省略零值,则需要条件打印:

if m != 0:
    print(f"{m} meter ", end="")
if cm != 0:
    print(f"{cm} centimeter ", end="")
if mm != 0:
    print(f"{mm} millimeter", end="")
print() # for the newline

相关问题 更多 >