给定一些任意浮点值,将该值限制在最小/最大范围的惯用方法是什么?即,如果您提供的值低于最小值,则返回最小范围值,如果您提供的值大于最大值,则返回最大范围值。否则返回原始浮点值。
我认为这种方法可行,但它没有给我正确的值:
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)
rust ×1