匹配浮点范围的替代方法 [英] Alternatives to matching floating point ranges

查看:29
本文介绍了匹配浮点范围的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一系列浮点范围比较的最佳方法是什么?要使用下面 GitHub 评论中的示例,

What's the best way to write a series of floating point range comparisons? To use the example from the GitHub comment below,

let color = match foo {
    0.0...0.1 => Color::Red,
    0.1...0.4 => Color::Yellow,
    0.4...0.8 => Color::Blue,
    _         => Color::Grey,
};

天真的解决方案将是一个痛苦的 if-else 链:

The naive solution would be a painful if-else chain:

let color = {
    if 0.0 <= foo && foo < 0.1 {
        Color::Red
    }
    else if 0.1 <= foo && foo < 0.4 {
        Color::Yellow
    }
    else if 0.4 <= foo && foo < 0.8 {
        Color:: Blue
    }
    else {
        Color::Grey
    }
}

这真的是最好的选择吗?一定有更好的写法吧?

Is that really the best option available? There must be a nicer way to write this, right?

匹配浮点数的替代方法有关,但这是用于范围比较的.

Related to Alternatives to matching floating points, but this is for range comparisons.

最初在跟踪问题中提到invalid_floating_point_literal_pattern,以及我经常遇到的问题.

Originally mentioned in the tracking issue for illegal_floating_point_literal_pattern, and something I'm running into constantly.

推荐答案

我个人会这样做:

#[derive(Debug, PartialEq)]
enum Color {
    Red,
    Yellow,
    Blue,
    Grey,
}

trait InRange {
    fn in_range(self, begin: Self, end: Self) -> bool;
}

impl InRange for f32 {
    fn in_range(self, begin: f32, end: f32) -> bool {
        self >= begin && self < end
    }
}

impl From<f32> for Color {
    fn from(f: f32) -> Color {
        match f {
            x if x.in_range(0.0, 0.1) => Color::Red,
            x if x.in_range(0.1, 0.4) => Color::Yellow,
            x if x.in_range(0.4, 0.8) => Color::Blue,
            _ => Color::Grey,
        }
    }
}

fn main() {
    assert_eq!(Color::from(0.2), Color::Yellow);
}

这篇关于匹配浮点范围的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆