给定一些任意浮点值,将该值限制在最小/最大范围的惯用方法是什么?即,如果您提供的值低于最小值,则返回最小范围值,如果您提供的值大于最大值,则返回最大范围值。否则返回原始浮点值。
我认为这种方法可行,但它没有给我正确的值:
fn main(){
dbg!(min_max(150.0, 0.0, 100.0));
//because 150.0 is greater than 100.0, should return 100.0
//currently returns 0.0
dbg!(min_max(-100.0, 0.0, 100.0));
//becuase -100.0 is below the minimum value of 0.0, should return 0.0
//currently returns 0.0
}
fn min_max(val: f32, min: f32, max: f32)->f32{
return val.max(max).min(min);
}
Run Code Online (Sandbox Code Playgroud)
pheki 的回答解释了为什么您的尝试不起作用,但还有一种专用于此任务的方法:clamp。
fn main(){\n dbg!(150.0_f32.clamp(0.0, 100.0)); // = 100.0\n dbg!((-100.0_f32).clamp(0.0, 100.0)); // = 0.0\n}\nRun Code Online (Sandbox Code Playgroud)\n(添加的_f32后缀是为了告诉 Rust 我们想要使用f32数字而不是可能的f64\xe2\x80\x94,否则程序将无法编译。它们只在这个小例子中是必要的,因为没有函数签名或指定我们要使用哪种类型的任何其他内容。)