python2 round()
时间: 2024-05-10 19:16:21 浏览: 11
在 Python 2 中,函数 `round()` 可以对浮点数进行四舍五入操作并返回整数。如果参数类型为浮点数,则返回最接近参数的整数。如果参数类型为整数,则返回参数本身。如果参数为 None,则会抛出 TypeError 异常。如果参数为复数,则会抛出 TypeError 异常。
例如:
```python
>>> round(3.1415926535)
3.0
>>> round(3.5)
4.0
>>> round(2.71828, 3)
2.718
>>> round(-1.5)
-2.0
>>> round(2)
2
>>> round(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object cannot be interpreted as a number
>>> round(2 + 3j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type complex doesn't define __round__ method
```
需要注意的是,在 Python 3 中,函数 `round()` 的行为有所改变。如果要在 Python 2 中使用 Python 3 中的 `round()` 函数,可以通过将参数转换为浮点数来实现。例如:
```python
>>> round(3.5)
4.0
>>> round(3.5, 0)
4.0
>>> round(float(3.5))
4
>>> round(float(3.5), 0)
4.0
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)