迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

在 Python 中不带余数的除法

作者:迹忆客 最近更新:2022/10/05 浏览次数:

使用 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,则函数返回最接近的整数。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便