pthon中取整的几个方法round、int、math
作者:野牛程序员:2023-11-22 12:17:03python阅读 2762
pthon中取整的几个方法round、int、math:
round
函数是一个内置函数,用于四舍五入到最接近的整数或指定小数位数的浮点数。
int
函数用于将一个数字或浮点数转换为整数。它不会进行四舍五入,而是直接截断小数部分。
math
模块提供了 floor
和 ceil
函数,分别用于向下取整和向上取整。floor
返回不大于输入参数的最大整数,而 ceil
返回不小于输入参数的最小整数。
下面是这些方法的示例用法:
# 使用 round 函数进行四舍五入 result_round = round(3.14) print(result_round) # 输出 3 # 使用 int 函数进行截断 result_int = int(3.14) print(result_int) # 输出 3 # 使用 math 模块的 floor 函数向下取整 import math result_floor = math.floor(3.14) print(result_floor) # 输出 3 # 使用 math 模块的 ceil 函数向上取整 result_ceil = math.ceil(3.14) print(result_ceil) # 输出 4
这些方法可以根据需求选择使用。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
