The absolute difference is a measure of the difference between two numbers but expressed as a positive number.
In other words, it’s taking the difference between two values (x - y) and then calculating the absolute value of the result.
Create a function that takes in two numbers a and b and returns their absolute difference.
Examples:
absDiff(3, 0) ➞ 3 absDiff(0, 3) ➞ 3 absDiff(10, -1) ➞ 11 absDiff(-5, -7) ➞ 2 absDiff(6, -6) ➞ 12 absDiff(1.5, 1.5) ➞ 0
Note:
Do not use the abs() function provided by Swift (it will defeat the purpose of the challenge)
Hints:
If
a is less then b, the absolute difference equals b - a. What if a is greater than or equal to b?
If
a < b, we should return b - a. Otherwise, we should return a - b. We can use an if statement to put this in code.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check