[英]Absolute value function in Rust
In this elementary Rust program a function calculates the absolute value of an integer, and main() helps in completing a statement with the result:在这个基本的 Rust 程序中,一个函数计算一个整数的绝对值,而 main() 帮助完成一个带有结果的语句:
fn main() {
let value = abs(-4);
println!("{}.", value);
}
fn abs(x: i32) -> i32 {
print!("The abs value of {} is ", x);
if x > 0 {
return x;
} else {
-x
}
}
Is there a way to print correctly the whole statement "The abs value of... is..." into the abs() function?有没有办法将整个语句“...的 abs 值是...”正确打印到 abs() 函数中? I tried unsuccessfully with我尝试失败
println!("The abs value of {} is {} ", x, x);
This always prints the value of the x parameter (eg -4, -4) so it's not correct.这总是打印 x 参数的值(例如 -4、-4),所以它不正确。
And with并与
println!("The abs value of {} is {} ", x, abs(x));
But here, for some reason, Rust is not happy with recursion, gives a warning at compilation and then doesn't run the program.但在这里,出于某种原因,Rust 对递归不满意,在编译时发出警告,然后不运行程序。
Try this to avoid recursion:试试这个以避免递归:
fn main() {
let value = abs(-4);
println!("{}.", value);
}
fn abs(x: i32) -> i32 {
let y = if x >= 0 { x } else { -x };
println!("The abs value of {} is {} ", x, y);
y
}
Output:输出:
The abs value of -4 is 4
4.
There are built-in .abs()
method for primitive types eg i8 , i16 , i32 , i64 , i128 , f32 , and f64 :原始类型有内置的.abs()
方法,例如i8 、 i16 、 i32 、 i64 、 i128 、 f32和f64 :
assert_eq!(10i32.abs(), 10);
assert_eq!((-10i32).abs(), 10);
The absolute value of
i32::min_value()
cannot be represented as ani32
, and attempting to calculate it will cause an overflow.i32::min_value()
的绝对值不能表示为i32
,尝试计算它会导致溢出。 This means that code in debug mode will trigger a panic on this case and optimized code will returni32::min_value()
without a panic.这意味着调试模式下的代码将在这种情况下触发恐慌,优化后的代码将返回i32::min_value()
而不出现恐慌。
The following code, will panic in debug mode (and returns -128
in release mode):以下代码将在调试模式下发生恐慌(并在发布模式下返回-128
):
fn main() {
let a = -128_i8;
println!("{}", a); // -128
let b = a.abs();
println!("{}", b); // -128
}
Since abs(-2_147_483_648_i32)
is 2_147_483_648_u32
, you may return u32
instead of i32
:由于abs(-2_147_483_648_i32)
是2_147_483_648_u32
,您可能会返回u32
代替i32
:
fn abs(x: i32) -> u32 {
if x >= 0 {
x as u32
} else if x == std::i32::MIN {
2_147_483_648_u32
} else {
-x as u32
}
}
fn main() {
let value = abs(std::i32::MIN); // i32::min_value() // -2_147_483_648i32
println!("{}.", value); // 2147483648
}
2147483648
The absolute value method is already defined ;绝对值法已经定义; you do not need to implement it yourself你不需要自己实现它
fn main() {
let value = abs(-4);
println!("{}.", value);
}
fn abs(x: i32) -> i32 {
let val = x.abs();
println!("The abs value of {} is {}", x, val);
val
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.