I want to define a function that can take either an integer or a floating-point number as an argument, and return the nearest integer (ie the input argument itself if it is already an integer). I tried this:
def toNearestInt(x):
return int(x+0.5)
but it doesn't work for negative integers.
>>> toNearestInt(3)
3
>>> toNearestInt(3.0)
3
>>> toNearestInt(3.49)
3
>>> toNearestInt(3.50)
4
>>> toNearestInt(-3)
-2
How can I fix it?
Python already has a builtin for this (more or less).
>>> round(-3, 0)
-3.0
>>> round(-3.5, 0)
-4.0
>>> round(-3.4, 0)
-3.0
>>> round(-4.5, 0)
-5.0
>>> round(4.5, 0)
5.0
Of course, you might want to wrap that in a call to int
...
def toNearestInt(x):
return int(round(x, 0))
You could keep your initial approach here and just check to see if the input is negative and add -0.5 in that case.
def toNearestInt(x):
a = 0.5
if x < 0:
a*=-1
return int(x+a)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.