The abs() function returns the absolute value of a number. This means that it returns a number's positive value. You can think of it as the distance away from zero.
Create your own function abs() that recreates this functionality.
Examples:
abs(-1.217197940) ➞ 1.21719794 abs(-544.0) ➞ 544 abs(250.3) ➞ 250.3 abs(0) ➞ 0 abs(-0.14) ➞ 0.14
Note:
Do not use the abs() function provided by Scala (it will defeat the purpose of the challenge)
Hints:
You can make use of
< operator with an if statement to check if n is negative.
You can add an
else statement to handle the case when n is positive.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check