Start learning free

LESSON 87 OF 348 · CONDITIONAL STATEMENTS - CHALLENGES

Find the absolute difference in Rust

Practice

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 Rust (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.
STEP 1 OF 3
    Ctrl + Enter to check

    Recreating Absolute Difference in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free