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

如何调试这个统计二维数组素数数量的C语言程序?

图中是我看到的运行输出

你的代码存在两处核心问题,导致素数统计结果始终为0:

  • 语法冗余错误:isprime函数结束后多写了一个多余的右大括号},实际编译运行时会产生语法问题,需直接删除。
  • 传参逻辑错误:main函数中调用primecount统计素数时,第三个参数错误传入了a[n][m]。该写法代表取二维数组中下标为n、m的单个元素,本身已经属于数组越界访问,且完全不符合primecount要求传入二维数组首地址的参数要求,函数内部无法读取到你输入的正确数组内容,因此统计结果恒为0,此处应将第三个参数改为a。
  • 额外缺失头文件:原代码没有引入标准输入输出头文件,部分编译器会直接报错,需在代码开头补充#include <stdio.h>。

修正后的完整代码如下:

#include <stdio.h>
int isprime(int n)
{
    int k;
    if (n <= 1)
        return 0;
    for (k = 2; k <= (n / 2); k++){
        if (n % k == 0)
         return 0;
    }
    return 1;
}
int primecount(int x, int y, int a[x][y]){
    int r, c, count = 0;
    for(r = 0; r < x; r++) {
        for(c = 0; c < y; c++) {
            if(isprime(a[r][c]))
            {
                    count++;
            }
        }
    }
    return count;
}
int main()
{
    int n, m, i, j, z;
    printf("Enter the Number of Rows: ");
    scanf("%d", &n);
    printf("\n");
    printf("Enter the Number of Columns: ");
    scanf("%d", &m);
    printf("\n");
    int a[n][m];
    printf("Enter the elements of the array: \n");
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < m; j++)
            scanf("%d", &a[i][j]);
    }
    z = primecount(n, m, a);
    printf("\n");
    printf("The Number of Prime Numbers in the array is: %d", z);
    printf("\n");
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:54:02