python中的int如何取整

29次阅读
没有评论

共计 437 个字符,预计需要花费 2 分钟才能阅读完成。

在 Python 中,可以使用以下几种方法对 int 进行取整操作:

  1. 向下取整(floor):使用 math 模块的 floor 函数来向下取整。例如,math.floor(3.9) 将返回 3。
import math
x = 3.9
result = math.floor(x)
print(result)  # 输出结果为 3 
  1. 向上取整(ceil):使用 math 模块的 ceil 函数来向上取整。例如,math.ceil(3.2) 将返回 4。
import math
x = 3.2
result = math.ceil(x)
print(result)  # 输出结果为 4 
  1. 四舍五入(round):使用内置函数 round 来进行四舍五入。例如,round(3.7) 将返回 4。
x = 3.7
result = round(x)
print(result)  # 输出结果为 4 

另外,可以通过对 int 值进行除法运算再取整,实现向下取整、向上取整和四舍五入。例如,int(3.9) 将返回 3,int(3.2) 将返回 3,int(3.7) 将返回 4。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-22发表,共计437字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)