且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有长堆if语句的情况下将float映射到枚举

更新时间:2023-09-10 08:04:10

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

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.