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/