乐闻世界logo
搜索文章和话题

How do I get an absolute value in Rust?

1个答案

1

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:

rust
fn 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:

shell
The 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:

rust
fn 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:

shell
The 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.

2024年7月1日 12:50 回复

你的答案