在二维数组中查找特定值的计数器

时间:2018-03-18 21:20:11

标签: c arrays

我想知道二维数组是否包含特定值。 以这个随机矩阵为例:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int m;
    int n;
    int mat[100][100];

    printf("Enter the number of rows: ");
    scanf("%d", &m);

    printf("\nEnter the number of columns: ");
    scanf("%d", &n);

    srand(time(NULL));

    printf("\n");

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            mat[i][j] = rand() % 21;
            printf("%d\t", mat[i][j]);
        }
        printf("\n");
    }
    printf("\n");

    return 0;
}

如何找出mat[i][j]数组中有多少个零(0)?

1 个答案:

答案 0 :(得分:0)

嗯,这取决于你是否允许在实际填写矩阵时保存这些信息?

int numZeroes = 0;
for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
        mat[i][j] = rand() % 21;

        if (mat[i][j] == 0) {
            numZeroes++;
        }

        printf("%d\t", mat[i][j]);
    }
    printf("\n");
}
printf("\n");

如果你不能,你只需要确定矩阵初始化后有多少个零,你需要强力搜索它,因为它根本没有排序,使用相同类型的嵌套循环你用于初始化它:

int numZeroes = 0;
for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
        if (mat[i][j] == 0) {
            numZeroes++;
        }
    }
相关问题