温馨提示×

c语言怎么筛选符合条件的数据

小亿
180
2023-12-07 13:17:27
栏目: 编程语言

在C语言中,可以使用循环和条件判断语句来筛选符合条件的数据。具体步骤如下:

  1. 定义一个数组或链表,存储待筛选的数据。
  2. 使用循环遍历数组或链表中的每个数据。
  3. 在循环中,使用条件判断语句来判断当前数据是否符合筛选条件。如果符合条件,则将该数据存储到另一个数组或链表中。
  4. 继续循环遍历剩余的数据,直到遍历完所有数据。
  5. 最后,得到的新数组或链表中存储的就是符合条件的数据。

例如,假设有一个整数数组,我们要筛选出所有大于等于10的数,可以使用以下代码:

#include <stdio.h>

int main() {
    int arr[] = {5, 12, 8, 20, 10, 15};
    int length = sizeof(arr) / sizeof(arr[0]);
    int newArr[length];
    int count = 0;
    
    for (int i = 0; i < length; i++) {
        if (arr[i] >= 10) {
            newArr[count] = arr[i];
            count++;
        }
    }
    
    printf("符合条件的数据:");
    for (int i = 0; i < count; i++) {
        printf("%d ", newArr[i]);
    }
    
    return 0;
}

运行以上代码,输出结果为:符合条件的数据:12 20 10 15。可以看到,新数组newArr中存储的就是符合条件的数据。

0