Python math.ceil()方法

Pythonmath.ceil() 方法是将一个数字四舍五入到大于给定数字的最小积分值的一种有效方法。如果给定的数字已经是一个整数,则返回精确的数字。

语法

math.ceil(x)

参数

x 任何正数或负数。

返回值

此方法的返回类型是一个整数,代表x 的上限。

例子

例子演示如何正确使用math.ceil()

代码片段:

import math
x=0.898762343
value=math.ceil(x)
print(f"The ceiling of {x} is {value}.")
x=-9.5555555
value=math.ceil(x)
print(f"The ceiling of {x} is {value}.")
x=10
value=math.ceil(x)
print(f"The ceiling of {x} is {value}.")

输出:

The ceiling of 0.898762343 is 1.
The ceiling of -9.5555555 is -9.
The ceiling of 10 is 10.

请注意,参数应该是一个有效的数字。数值可以是正数,也可以是负数。

例子展示了在使用时出现的错误math.ceil()

代码片段:

import math
##entering a string
x="Hi"
value=math.ceil(x)
print(f"The ceiling of {x} is {value}.")
##entering a list
x=[1,2,3]
value=math.ceil(x)
print(f"The ceiling of {x} is {value}.")
##entering complex numbers
x=1+5j
value=math.ceil(x)
print(f"The ceiling of {x} is {value}.")
##entering an infinite number
x=math.inf
value=math.ceil(x)
print(f"The ceiling of {x} is {value}.")

输出:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    value=math.ceil(x)
TypeError: must be a real number, not str
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    value=math.ceil(x)
TypeError: must be a real number, not a list
^ATraceback (most recent call last):
  File "main.py", line 7, in <module>
    value=math.ceil(x)
TypeError: can't convert complex to float
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    value=math.ceil(x)
OverflowError: cannot convert float infinity to integer

上面的代码片段显示了使用math.ceil() 方法时所有可能的语法错误。