当前位置:首页>开发>正文

python中round函数怎么用 python中的小白问题求教

2023-07-05 12:43:32 互联网 未知 开发

 python中round函数怎么用 python中的小白问题求教

python中round函数怎么用

描述
round() 方法返回浮点数x的四舍五入值。
语法
以下是 round() 方法的语法:
round( x [, n] )

参数
x -- 数值表达式。
n -- 数值表达式。
返回值
返回浮点数x的四舍五入值。
实例
以下展示了使用 round() 方法的实例:
#!/usr/bin/python

print "round(80.23456, 2) : ", round(80.23456, 2)
print "round(100.000056, 3) : ", round(100.000056, 3)
print "round(-100.000056, 3) : ", round(-100.000056, 3)

以上实例运行后输出结果为:
round(80.23456, 2) : 80.2round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0

python中的小白问题求教

Python 3.2.3 (default, Oct 19 2012, 20:13:42)
[GCC 4.6.3] on linuxType "copyright", "credits" or "license()" for more information.
==== No Subprocess ====
>>> import math

>>> math.ceil(0.5)
>>> x = input(x: )
x: 1>>> print(x)
1>>>

如上,将一个0.5四舍五入到1要用math模块的ceil()函数向上取整,因为默认的round()四舍五入函数是会遇到×××.5会取偶数的。例如1.5--》2 而0.5--》0
至于print语法错误,是因为python 3.x版中print是一个函数,所以要用调用函数的形式,要有括号。
python3.x 是不向下兼容2.x的

最新文章