You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

查询二维数组中特定值的出现次数及判断其是否存在

二维数组的两个常见操作实现(基于随机矩阵生成代码)

Got it, let's build on the random 2D matrix code you shared to implement your two requested features. I'll break this down step by step so it's easy to follow.

1. 统计特定值的出现次数

The core logic here is straightforward: iterate over every element in the 2D array, compare each element to your target value, and keep a running counter that increments whenever there's a match. Doing this in a single loop alongside the presence check saves us from redundant iterations.

2. 判断是否包含特定值

For this check, we can flip a flag to "found" as soon as we encounter the target value during our loop. If we finish going through all elements without hitting the target, we know it's not present in the array.


完整整合代码

Here's the full, working code that generates the random matrix, takes your target value as input, and handles both tasks efficiently:

#include <stdio.h>
#include <stdlib.h>
#include <time.h> // Don't forget this header for time()

int main() {
    int m, n, target;
    int mat[100][100];
    int occurrenceCount = 0;
    int isValuePresent = 0;

    // Get matrix dimensions from user
    printf("Enter the number of rows: ");
    scanf("%d", &m);
    printf("\nEnter the number of columns: ");
    scanf("%d", &n);

    // Initialize random seed to get different matrices each run
    srand(time(NULL));
    printf("\nGenerated Random 2D Matrix:\n");

    // Generate and print the random matrix (values 0-20)
    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");
    }

    // Get target value to check from user
    printf("\nEnter the target value to look for: ");
    scanf("%d", &target);

    // Perform both count and presence check in one loop
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (mat[i][j] == target) {
                occurrenceCount++;
                isValuePresent = 1; // Mark as found once, no need to check again
            }
        }
    }

    // Output the results clearly
    printf("\nResult Summary:\n");
    printf("The value *%d* appears %d times in the matrix.\n", target, occurrenceCount);
    if (isValuePresent) {
        printf("✅ The matrix DOES contain the value %d.\n", target);
    } else {
        printf("❌ The matrix does NOT contain the value %d.\n", target);
    }

    return 0;
}

关键细节说明

  • Added <time.h>: Your original code was missing this header, which is required for time(NULL) to work with srand() (otherwise you'd get a compile error).
  • Efficient single loop: We handle both tasks in one pass through the array instead of looping twice, which saves computation time.
  • Clear user feedback: The results are formatted to be easy to read, with emphasis on the target value and clear success/failure indicators.

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:40:20