传感器三元数组数据更新逻辑优化:求替代冗余If-Else方案
传感器数据采集的数组逻辑优化方案
需求与现状
我正在开发一个传感器数据采集项目,需将数据存入长度为3的数组three_values_list,规则为:数组始终保存采集到的最大三个值,按降序排列(索引[0]为最大值,[2]为最小值);新数据需与现有数据比较后决定插入或丢弃——仅当新数据大于当前数组中的最小值时才插入,插入后保持降序并移除原最小值;若新数据与数组中已有值重复或小于等于最小值,则直接丢弃。
目前采用If-Else逐次比较实现,代码如下:
if (New_value > three_values_list[2]) { three_values_list[0] = three_values_list[1]; three_values_list[1] = three_values_list[2]; three_values_list[2] = New_value; } else if (three_values_list[2] > New_value > three_values_list[1]) { three_values_list[0] = three_values_list[1]; three_values_list[1] = New_value; } else if (three_values_list[1] > New_value > three_values_list[0]) { three_values_list[0] = New_value; }
该方案需要逐次判断新值的位置,逻辑繁琐;尝试过三元运算符,但可读性差且代码冗长,希望找到更优实现。
示例输入输出
- 串行输入数据:
12 22 21 23 22 4 12,预期输出:23 22 21 - 新输入
20,输出保持:23 22 21 - 新输入
28,输出变为:28 23 22 - 新输入
24,输出变为:28 24 23 - 新输入
28,输出保持:28 24 23
优化实现方案
针对长度固定为3的数组,可采用临时数组排序+去重+截断的方式,避免逐次比较,代码简洁且可读性强:
C语言实现
// 1. 将当前数组值与新值存入临时数组 int temp[4] = {three_values_list[0], three_values_list[1], three_values_list[2], New_value}; // 2. 对临时数组进行降序排序 for (int i = 0; i < 3; i++) { for (int j = i + 1; j < 4; j++) { if (temp[i] < temp[j]) { int swap = temp[i]; temp[i] = temp[j]; temp[j] = swap; } } } // 3. 去重并提取前3个唯一的最大值 int unique_temp[3]; int idx = 0; for (int i = 0; i < 4 && idx < 3; i++) { // 跳过重复值 if (i == 0 || temp[i] != temp[i-1]) { unique_temp[idx++] = temp[i]; } } // 4. 补全数组(处理初始值不足3个的情况) while (idx < 3) { unique_temp[idx] = unique_temp[idx-1]; idx++; } // 5. 将结果赋值回原数组 three_values_list[0] = unique_temp[0]; three_values_list[1] = unique_temp[1]; three_values_list[2] = unique_temp[2];
方案优势
- 无需逐次判断新值的位置,逻辑更清晰
- 自动处理重复值,符合需求中“重复值丢弃”的规则
- 代码扩展性强:若后续需要调整数组长度,仅需修改临时数组大小和截断长度即可
内容的提问来源于stack exchange,提问作者Diracx
相关产品推荐
相关产品推荐

