Python基本使用圆形

时间:2017-01-27 21:58:02

标签: python rounding

所以我上周开始学习编程,现在我自己也搞不清楚了。我需要最终答案为“大小在24到192之间”。但如果我绕它,它给我192.0。我需要改变什么?

minp = 23.75
maxp = 192.4
minp1 = round(minp, 0)
maxp1 = round(maxp, 0)
print("Size between " + str(minp1) + " to " + str(maxp1) + ".")

2 个答案:

答案 0 :(得分:2)

由于minp1maxp1的类型仍为 float s ,您可以将其更改为 {{1通过将它们传递给int构造函数来

int(..)

或在终端中:

minp = 23.75
maxp = 192.4
minp1 = int(round(minp, 0))
maxp1 = int(round(maxp, 0))
print("Size between " + str(minp1) + " to " + str(maxp1) + ".")

尽管如此,自己进行字符串处理/连接并不是一个好主意。您最好使用formatting string对其进行格式化,例如:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> minp = 23.75
>>> maxp = 192.4
>>> minp1 = int(round(minp, 0))
>>> maxp1 = int(round(maxp, 0))
>>> print("Size between " + str(minp1) + " to " + str(maxp1) + ".")
Size between 24 to 192.

此处minp = 23.75 maxp = 192.4 minp1 = round(minp, 0) maxp1 = round(maxp, 0) print("Size between %d to %d."%(minp1,maxp1))代表" 有符号整数十进制"。因此,通过使用格式,Python将在%d位置填充变量,这些变量很优雅,并且需要较少的思考。

答案 1 :(得分:0)

如果您想将数字保留为float并特别以整数格式输出:

def r(val):
    return "{0:.0f}".format(round(val))

minp = 23.75
maxp = 192.4
print("Size between {0} to {1}.".format(r(minp), r(maxp)))

<强>结果:

Size between 24 to 192.
相关问题