问题描述
|
我有一个设备驱动程序,该设备驱动程序使用以下算法将从传感器接收的值(无界限范围)转换为其他值(界限范围)。
传感器的值通常在0-200范围内,但可以超过该范围,最大值约为4000(仅当您极端使用传感器时才会发生这种情况)。我基本上需要一个可以执行以下操作但没有巨型without0ѭ的函数,因此它更灵活。
它需要输入值,步长(在这种情况下为20.0f)和最大输出(在这种情况下为10)。
/* disregard the floating point numbers,I can cast them to int */
if (value <= 20.0f)
return 0;
else if (value <= 40.0f)
return 1;
else if (value <= 60.0f)
return 2;
else if (value <= 80.0f)
return 3;
else if (value <= 100.0f)
return 4;
else if (value <= 120.0f)
return 5;
else if (value <= 140.0f)
return 6;
else if (value <= 160.0f)
return 7;
else if (value <= 180.0f)
return 8;
else if (value <= 190.0f)
return 9;
else if (value >= 200.0f)
return 10;
return 0;
解决方法
int step(double value,int step,int maximum) {
return min(int(value / step),maximum);
}
编辑:正如@DSM所指出的,这有一个fencepost错误,应该是这样的:
int step(double value,int maximum) {
return min(int((value-1) / step),maximum);
}
, 假设您有min
,看起来像您想要的
min(0,(int)((min(220,value) - 20) / 20))
(编辑,对于之前的最小/最大混淆感到抱歉!)
, 我会做这样的事情:
struct temp_thresholds {
float upper_bound;
int ret_val;
} thresholds = {
{ 20.0f,0},{ 40.0f,1},{ 80.0f,2},// ..
{ 190.0f,9},{ 200.0f,// strange,and doesn\'t quite match your code
{ MAX_FLOAT,10},// find a constant like this
};
int foo(float value)
{
// if the table were big enough,you could do binary search
for (int i = 0; i < sizeof thresholds / sizeof thresholds[0]; ++i)
if (value <= thresholds[i].upper_bound)
return thresholds[i].ret_value;
assert(0);
return 0;
}