algorithm - 对于太多 if else 语句的更好方法

标签 algorithm if-statement math

if ( x < 275 && x >= 0 ) 
   f = 275
else if ( x < 450 && x >= 275) (right side comparison always previous left side default comparison value
   f = 450
else if ( x < 700 && x >= 450) 
   f = 700
else if ( x < 1000 && x >= 700) 
   f = 1000
..... and more 

有没有什么方法或数学公式方法可以消除这个多重 if else 语句以减少代码需求?

最佳答案

这是 C 中的一些东西(但很容易移植到几乎任何东西)。它错过了几个条件(x < 0 和 x >“已知最大”)当您只有 4 个值时它不会增加太多值(value),但是您拥有的值越多,删除的代码就越多。请注意,它会减慢速度,但除非您有大量可能值,否则您是否会注意到它值得怀疑。

int getF(int x)
{
    /* possibleValues must be sorted in ascending order */
    int possibleValues[] = { 275, 450, 700, 1000 };
    for(int i = 0; i < sizeof(possibleValues) / sizeof(possibleValues[0]); i++)
    {
        int pv = possibleValues[i];
        if (x < pv)
        {
            return pv;
        }
    }
    /* fall thru "error" handle as you see fit */
    return x;
}

关于algorithm - 对于太多 if else 语句的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38365024/

相关文章:

algorithm - 给定代码的时间复杂度是多少?

python - 求矩阵内 1s 的最大平方时出错

c++ - OCaml 中的快速位数组

algorithm - 如何计算 log(n!) = Ω( n*log(n))?

在等距投影中将 3D 坐标转换为 2D

java - 调色板算法输出从红色到蓝色的颜色网格

Powershell 仅当基于列 1 的组的列 2 -cge 列 3 时才显示行

matlab - find(isnan) 的对面

javascript - 错误: Invalid left-hand side in assignment

java - Math#random 不是那么随机吗?