如何在没有长堆if语句的情况下将float映射到枚举 [英] How to map a float to an enum without a long stack of if statements

查看:122
本文介绍了如何在没有长堆if语句的情况下将float映射到枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个浮动,如何将它映射到枚举如

Given a float, how to map it to an enum like


{FAIL,POOR,OK,GOOD,EXCELLENT,PERFECT}

{FAIL, POOR, OK, GOOD, EXCELLENT, PERFECT}

如果除法不均匀。


0.0-0.4是失败

0.4-0.6是不好的...
...

0.8-0.999 ..是优秀的

1.0是完美的

0.0-0.4 is FAIL
0.4-0.6 is POOR
...
0.8-0.999.. is EXCELLENT
1.0 is PERFECT

浮动是根据游戏中所有玩过的等级计算的等级值。它的范围从0..1,包括两者。通常不需要超过10个分区,但是在开发过程中间距会受到调整。

The float is a rating value calculated from all the played levels in a game. It ranges from 0..1, both inclusive. There are normally no more than about 10 divisions needed, but the spacings are subject to tuning during development.

我目前正在使用一堆if..else语句。这是正确的方法吗?它看起来有点脆弱。

I'm currently using a stack of if..else statements. Is that the right way to do it? It seems a bit brittle.

推荐答案

使用结构数组 - 静态分配或动态 - 然后使用简单的例程进行搜索它 - 如果它的小只是迭代,如果它的大,你可以做二分搜索。

Use an array of structs - either statically allocated or dynamic - and then a simple routine to search it - if its small just iterate, if its large you can do binary search.

如你所知,最小(0.0)和最大(1.0)你只需要存储范围和枚举值的上限。例如:

As you know the minimum (0.0) and maximum (1.0) you only need to store the upper-bound of the range and enum value. E.g:

typedef enum {FAIL, POOR, OK, GOOD, EXCELLENT, PERFECT} Rating;

typedef struct
{
   float upperBound;
   Rating score;
} RatingDivision;

static RatingDivision Divisions[] =
{
   { 0.4, FAIL },
   { 0.6, POOR },
   ...
   { 0.999, EXCELLENT },
   { 1.0, PERFECT }
};

现在 sizeof(分部)/ sizeof(RatingDivision)会告诉你条目数(二进制搜索所需),或者只是迭代直到你要找的值是< = Divisions [i] .upperBound 返回 Divisions [i] .score upperBound 到达 1.0 没有匹配并处理错误。

Now sizeof(Divisions)/sizeof(RatingDivision) will tell you the number of entries (needed for binary search), or just iterate until the value you're looking for is <= Divisions[i].upperBound returning Divisions[i].score or the upperBound reaches 1.0 with no match and handle the error.

这篇关于如何在没有长堆if语句的情况下将float映射到枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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