forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabs.rs
More file actions
38 lines (33 loc) · 780 Bytes
/
abs.rs
File metadata and controls
38 lines (33 loc) · 780 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/// This function returns the absolute value of a number.\
/// The absolute value of a number is the non-negative value of the number, regardless of its sign.\
///
/// Wikipedia: <https://en.wikipedia.org/wiki/Absolute_value>
pub fn abs<T>(num: T) -> T
where
T: std::ops::Neg<Output = T> + PartialOrd + Copy + num_traits::Zero,
{
if num < T::zero() {
return -num;
}
num
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_negative_number_i32() {
assert_eq!(69, abs(-69));
}
#[test]
fn test_negative_number_f64() {
assert_eq!(69.69, abs(-69.69));
}
#[test]
fn zero() {
assert_eq!(0.0, abs(0.0));
}
#[test]
fn positive_number() {
assert_eq!(69.69, abs(69.69));
}
}