Obtaining the absolute value of a number in Rust can be achieved by using the abs() method provided by the standard library, which works for both integer and floating-point types. Here are two examples: one for integers and another for floating-point numbers.
Example 1: Absolute Value for Integers
For integers, we can use the abs() method of the i32 type. For example:
rustfn main() { let num = -10; let absolute_value = num.abs(); println!("The absolute value of {} is {}", num, absolute_value); }
In this example, the variable num is set to -10, and after applying the .abs() method, absolute_value becomes 10. The output is:
shellThe absolute value of -10 is 10
Example 2: Absolute Value for Floating-Point Numbers
For floating-point numbers, we can use the abs() method of the f64 type. For example:
rustfn main() { let num = -3.14; let absolute_value = num.abs(); println!("The absolute value of {} is {}", num, absolute_value); }
In this example, num is -3.14, and after applying the .abs() method, absolute_value becomes 3.14. The output is:
shellThe absolute value of -3.14 is 3.14
These examples demonstrate how to simply and effectively use Rust's standard library method abs() to obtain the absolute value of any numeric type, which is very useful for data processing and mathematical operations.