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()
方法时所有可能的语法错误。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。