在 Python 中不带余数的除法
使用 floor 除法运算符 //
不带余数的除法,例如 result_1 = 25 // 4
. floor除法运算符将始终返回一个整数,就像使用数学除法并将 floor()
函数应用于结果一样。
result_1 = 25 // 4
print(result_1) # 👉️ 6
result_2 = 25 / 4
print(result_2) # 👉️ 6.25
我们使用了 floor 除法 //
运算符来进行无余数除法。
整数的除法
/
产生一个浮点数,而整数的floor除法//
产生一个整数。
使用 floor 除法运算符的结果是数学除法的结果,将 floor()
函数应用于结果。
my_num = 50
print(my_num / 5) # 👉️ 10.0 (float)
print(my_num // 5) # 👉️ 10 (int)
我们可以像使用 floor 除法 //
运算符一样使用 math.floor()
方法。
import math
result_1 = math.floor(25 / 4)
print(result_1) # 👉️ 6
result_2 = 25 / 4
print(result_2) # 👉️ 6.25
math.floor
方法返回小于或等于所提供数字的最大整数。
还有一个 math.ceil()
方法。
import math
result_1 = math.ceil(25 / 4)
print(result_1) # 👉️ 7
result_2 = 25 / 4
print(result_2) # 👉️ 6.25
math.ceil
方法返回大于或等于所提供数字的最小整数。
如果要在除法时四舍五入到最接近的整数,也可以使用 round()
函数。
result_1 = round(26 / 4)
print(result_1) # 👉️ 6
result_2 = 26 / 4
print(result_2) # 👉️ 6.5
# --------------------------------
print(round(6.5)) # 👉️ 6
print(round(6.51)) # 👉️ 7
round
函数采用以下 2 个参数:
- number 小数点后四舍五入到 ndigits 精度的数字
- ndigits 小数点后的位数,运算后应有的数(可选)
round
函数返回小数点后四舍五入到 ndigits 精度的数字。
如果省略 ndigits,则函数返回最接近的整数。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。