Python math.floor() 方法用于计算不大于指定数字的最近值。例如,浮点数 2.3 的 floor 值为 2。
所涉及的过程几乎类似于估计或四舍五入技术。当下限值 2.3 为 2 时,会出现差异,但下限值 2.9 也将为 2;与估计技术不同,后者将 2.9 四舍五入为 3 而不是 2。
注意 − 这个函数不能直接访问,所以我们需要导入 math 模块,然后我们需要使用 math static object 调用这个函数。
语法
以下是 Python math.floor() 方法的语法 -
math.floor( x )
参数
- x − 这是一个数值对象。
返回值
此方法返回小于 x 的最大整数。
例以下示例显示了 Python math.floor() 方法的用法。在这里,我们将创建两个具有正值和负值的数值对象,并且这两个对象的楼层值都使用此方法计算。
import math # This will import math module
# Create two numeric objects x and y
x = 56.17
y = -33.89
# Calculate and display the floor value of x
res = math.floor(x)
print("The floor value of x:", res)
# Calculate and display the floor value of y
res = math.floor(y)
print("The floor value of y:", res)
当我们运行上述程序时,它会产生以下结果——
The floor value of x: 56
The floor value of y: -34
The floor value of y: -34
例
但是,此方法不会接受除数字对象以外的任何值作为其参数。
在此示例中,让我们尝试将包含数字对象的列表作为参数传递给此方法,并检查它是否计算所有对象的下限值。
import math # This will import math module
# Create a list containing numeric objects
x = [15.36, 56.45, 76.33, 6.04]
# Calculate the floor value for the list
res = math.floor(x)
print("The floor value of x:", res)
在执行上述程序时,将引发 TypeError ,如下所示 -
Traceback (most recent call last):
File "main.py", line 7, in
res = math.floor(x)
TypeError: must be real number, not list
File "main.py", line 7, in
res = math.floor(x)
TypeError: must be real number, not list
例
要使用此方法返回列表中数字对象的 floor 值,可以使用 loop 语句。
我们正在创建一个包含 number 对象的列表,其 floor 值将使用 floor() 方法计算。然后,我们尝试使用 for 循环迭代这个列表;对于每次迭代,都会将一个 number 对象作为参数传递给此方法。由于列表中的对象都是数字,因此该方法不会引发错误。
import math # This will import math module
# Create a list containing numeric objects
x = [15.36, 56.45, 76.33, 6.04]
ln = len(x)
# Calculate the floor value for the list
for n in range (0, ln):
res = math.floor(x[n])
print("The floor value of x[",n,"]:", res)
现在让我们执行给定的程序,结果显示如下 -
The floor value of x[ 0 ]: 15
The floor value of x[ 1 ]: 56
The floor value of x[ 2 ]: 76
The floor value of x[ 3 ]: 6
The floor value of x[ 1 ]: 56
The floor value of x[ 2 ]: 76
The floor value of x[ 3 ]: 6
例
我们可以在 Python 的许多实际应用中实现这个功能。
例如,我们可以尝试检索小数的整数部分和小数部分。为此,我们将创建一个具有 float 值的对象。此对象作为参数传递给 floor() 方法,以便检索此数字的整数部分;而使用 1 计算这个数字的模数将检索其小数部分。
import math # This will import math module
# Create a float object
x = 123.65
# Using floor() method, retrieve its integer part
int_part = math.floor(x)
# Calculate the modulus of x by 1 to retrieve the decimal part
dec_part = x % 1
# Display the results
print("The integer part of x is:", int_part)
print("The decimal part of x is:", dec_part)
在执行上述程序时,结果如下所示 -
The integer part of x is: 123
The decimal part of x is: 0.6500000000000057
The decimal part of x is: 0.6500000000000057