【问题标题】:Efficient If-Else Handling高效的 If-Else 处理
【发布时间】:2023-02-09 20:14:30
【问题描述】:

我正在做一个项目,其中我从传感器收集数据并将数据存储在大小为 3 的数组中。数据存储是这样的,它总是在索引 [2] 中存储最大值,在索引 [0] 中存储最小值,并且新数据进来的应该与已经存在的数据进行比较,并相应地在数组中排序或被丢弃。

我就是这样做的

    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;
    }

我希望更有效地做到这一点,而不仅仅是单独比较。

我也使用过三元运算符,但这似乎太大而且不太可读,有没有更好的方法来做到这一点?

【问题讨论】:

  • a > b > c 并不代表你认为它在 C 中的含义。我认为你的意思是 a > b && b > c

标签: arrays c sorting embedded


【解决方案1】:

你只能比较两个值,所以你需要这样的东西:

}else if((three_values_list[2] > New_value) && (New_value > three_values_list[1])){

【讨论】:

    【解决方案2】:

    您可以使用一个函数而不是多个 if 条件。 JS中的解决方案:

    function updateThreeValuesList(three_values_list: number[], newValue: number) {
      three_values_list.push(newValue);
      three_values_list.sort((a, b) => b - a);
      three_values_list.slice(0, 3);
    }
    

    上面的代码首先将新值推送到 three_values_list,然后对列表进行降序排序,并对排序后的列表的前三个元素进行切片。

    C 中的解决方案:

    void insert_value(int *three_values_list, int new_value) {
      int i;
    
      for (i = 0; i < 3; i++) {
        if (new_value > three_values_list[i]) {
          break;
        }
      }
    
      if (i < 3) {
        int j;
    
        for (j = 2; j > i; j--) {
          three_values_list[j] = three_values_list[j - 1];
        }
    
        three_values_list[i] = new_value;
      }
    }
    

    【讨论】:

    • 这不是 C 代码。
    • 也更新了 C 解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多