相关疑难解决方法(0)

将 Rust 中的浮点值限制为最小/最大范围

给定一些任意浮点值,将该值限制在最小/最大范围的惯用方法是什么?即,如果您提供的值低于最小值,则返回最小范围值,如果您提供的值大于最大值,则返回最大范围值。否则返回原始浮点值。

我认为这种方法可行,但它没有给我正确的值:

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

5
推荐指数
1
解决办法
4673
查看次数

标签 统计

rust ×1