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

统计二维数组中不含0的行数与列数的C++入门实现咨询

遍历二维数组检查所有行列是否含0的解决方案

要覆盖整个二维数组的所有元素,只需要用两层嵌套循环:外层循环遍历每一行,内层循环遍历当前行的每一列,逐个检查元素是否为0。以下是符合你要求的实现:

完整代码(无vector,仅用基础循环)

#include <iostream>
using namespace std;

int main() {
    // 示例二维数组,你可以替换成自己的数组
    int arr[3][4] = {
        {1, 2, 0, 3},
        {4, 5, 6, 7},
        {0, 8, 9, 10}
    };
    // 定义数组的行数和列数,方便后续修改
    const int totalRows = 3;
    const int totalCols = 4;

    // 遍历每一行,检查是否含0
    int currentRow = 0;
    while (currentRow < totalRows) {
        int currentCol = 0;
        bool rowHasZero = false;
        // 内层循环遍历当前行的所有列
        while (currentCol < totalCols) {
            if (arr[currentRow][currentCol] == 0) {
                rowHasZero = true;
                // 找到0后直接跳出内层循环,不用继续扫当前行
                break;
            }
            currentCol++;
        }
        cout << "第" << currentRow + 1 << "行:" << (rowHasZero ? "包含0" : "不包含0") << endl;
        currentRow++;
    }

    // 额外:遍历每一列检查是否含0(对应你之前能做的单列扫描扩展)
    cout << "\n列检查结果:" << endl;
    int currentCol = 0;
    while (currentCol < totalCols) {
        int currentRow = 0;
        bool colHasZero = false;
        while (currentRow < totalRows) {
            if (arr[currentRow][currentCol] == 0) {
                colHasZero = true;
                break;
            }
            currentRow++;
        }
        cout << "第" << currentCol + 1 << "列:" << (colHasZero ? "包含0" : "不包含0") << endl;
        currentCol++;
    }

    return 0;
}

关键说明

  • 外层循环控制行索引,内层循环控制列索引,用while循环实现,完全符合你要求的仅用循环的限制。
  • 用totalRows和totalCols常量存储数组的行列数,避免硬编码,后续改数组大小只需要改这两个值就行。
  • 每次检查一行/列时,用bool变量标记是否找到0,找到后用break提前终止当前循环,提升效率(也可以不用break,继续扫完所有元素,看你需求)。
  • 全程只用C++基础语法,没有用到vector,适配大一第一学期的知识范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:05:22