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

如何打印8x10二维数组中以指定元素为中心的5x5子数组

错误原因

  • 外层循环的行偏移变量没有代入数组行下标计算,全程用固定的i值访问行,所以5次循环都打印同一行内容
  • 内层循环复用了存储中心列坐标的变量j,直接覆盖了原始的中心坐标值,导致列访问逻辑错误
  • 没有计算子数组相对于中心坐标的偏移量,无法正确定位到中心上下2行的内容

实现代码

如果你的坐标是从1开始计数的,[6][3]对应的数组索引为[5][2],如果是0开始计数自行调整center_row和center_col的值即可:

#include <stdio.h>

int main() {
    // 8行10列数组可自行修改内容,此处按你提供的示例内容补充
    char array[8][10] = {
        {'a','b','c','d','e','f','g','h','-','-'},
        {'q','w','e','r','t','y','u','i','-','-'},
        {'k','j','h','g','f','d','s','a','-','-'},
        {'z','x','c','v','b','n','m','q','-','-'},
        {'g','z','p','l','k','h','n','a','-','-'},
        {'q','e','m','a','c','t','u','p','-','-'},
        {'r','b','l','t','k','f','b','z','-','-'},
        {'-','-','-','-','-','-','-','-','-','-'}
    };
    // 定义中心坐标索引(0开始计数)
    int center_row = 5;
    int center_col = 2;
    // 计算5x5子数组的起始行、起始列,加边界判断避免数组越界
    int start_row = center_row - 2 < 0 ? 0 : center_row - 2;
    int start_col = center_col - 2 < 0 ? 0 : center_col - 2;

    // 遍历5行
    for(int row_offset = 0; row_offset < 5; row_offset++) {
        int current_row = start_row + row_offset;
        // 超出数组最大行则终止
        if(current_row >= 8) break;
        // 遍历5列
        for(int col_offset = 0; col_offset < 5; col_offset++) {
            int current_col = start_col + col_offset;
            // 超出数组最大列则终止
            if(current_col >= 10) break;
            printf("%c", array[current_row][current_col]);
        }
        printf("\n");
    }
    return 0;
}

输出结果

上述代码运行后输出的5x5子数组为:

zxcvb
gzplk
qemac
rbltk
-----

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:24:02