带有Python示例的math.modf()方法
Pythonmath.modf()方法
math.modf()方法是数学模块的库方法,用于获取数字的小数部分和整数部分。它接受一个数字(整数或浮点数),并返回一个包含该数字的小数部分和整数部分的元组。
注意:
数字的整数部分也以float形式返回
如果数字是整数,则小数部分将是0.0
如果数字为负数,则两个部分均为负数
如果传递了除数字以外的任何内容,则该方法返回类型错误“TypeError:需要浮点数”
它的语法math.modf()方法:
math.modf(n)
Parameter(s):n-整数或浮点数。
返回值:tuple–返回包含数字n的小数部分和整数部分的元组。
示例
Input: a = 10.23 #函数调用 print(math.modf(a)) Output: (0.23000000000000043, 10.0)
Python代码演示示例math.modf()方法
#Python代码演示示例 # math.modf() method #导入数学模块 import math #数字 a = 10 b = 10.23 c = -10 d = -10.23 #打印小数和整数部分 # of the numbers by using math.modf()print("modf(a): ", math.modf(a)) print("modf(b): ", math.modf(b)) print("modf(c): ", math.modf(c)) print("modf(d): ", math.modf(d))
输出结果
modf(a): (0.0, 10.0)modf(b): (0.23000000000000043, 10.0)modf(c): (-0.0, -10.0)modf(d): (-0.23000000000000043, -10.0)