问题
def my_abs(value):
"""Returns absolute value without using abs function"""
if value < 5 :
print(value * 1)
else:
print(value * -1)
print(my_abs(3.5))
that's my code so far but the quiz prints, for example -11.255 and 200.01 and wants the opposite for example it wants 11.255 back and -200.01
回答1:
What does 5 have to do with absolute value?
Following your logic:
def my_abs(value):
"""Returns absolute value without using abs function"""
if value <= 0:
return value * -1
return value * 1
print(my_abs(-3.5))
>> 3.5
print(my_abs(3.5))
>> 3.5
Other, shorter solutions also exist and can be seen in the other answers.
回答2:
A simple solution for rational numbers would be
def my_abs(value):
if value<0:
return -value
return value
回答3:
Why do you want to check if value < 5?
Anyways, to replicate the abs function:
def my_abs(value):
return value if value >=0 else -1 * value
回答4:
The solutions so far don't take into account signed zeros. In all of them, an input of either 0.0 or -0.0 will result in -0.0.
Here is a simple and (as far as I see) correct solution:
def my_abs(value):
return (value**2)**(0.5)
来源:https://stackoverflow.com/questions/38587114/how-to-get-absolute-value-without-abs-function