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

如何将4×4二维数组向上循环移位?现有C++代码无法得到预期结果

问题分析与修正

你的代码存在两处核心错误:

  • 临时变量tmp固定取了第三行第0列的元素(arr[3][0]),没有针对当前处理的列获取正确的待移位元素
  • 列内元素的移位方向搞反,导致无法实现行整体向上循环的效果

另外变量命名过于模糊(比如r2、c的含义不明确),也增加了调试难度。

以下是两种可行的修正方案:

方案一:按行直接处理(更直观)

既然需求是将所有行向上循环移位一行(原第一行移到最后,其余行上移),可以直接操作整行数据:

#include <iostream>
#include <string>
using namespace std;

void cycleup(int arr[4][4])
{
    // 保存第一行的所有元素
    int tmpRow[4];
    for (int col = 0; col < 4; ++col) {
        tmpRow[col] = arr[0][col];
    }
    // 将第1-3行依次上移一行
    for (int row = 0; row < 3; ++row) {
        for (int col = 0; col < 4; ++col) {
            arr[row][col] = arr[row + 1][col];
        }
    }
    // 将保存的第一行放到最后一行
    for (int col = 0; col < 4; ++col) {
        arr[3][col] = tmpRow[col];
    }
}

int main()
{
    int arcg[4][4] = {{3, 7, 6, 5}, {5, 8, 2, 4}, {9, 7, 3, 1}, {8, 2, 1, 0}};

    cycleup(arcg);
    for (int row = 0; row < 4; ++row) {
        for (int col = 0; col < 4; ++col)
            cout << "\t" << arcg[row][col];
        cout << endl;
    }
}

方案二:按列修正原逻辑

行向上循环移位一行等价于每一列的元素向上循环移位一行(原列首元素移到列尾,其余元素上移),修正原列处理的逻辑:

#include <iostream>
#include <string>
using namespace std;

void cycleup(int arr[4][4])
{
    // 遍历每一列
    for (int col = 0; col < 4; ++col) {
        // 保存当前列的第一个元素
        int tmp = arr[0][col];
        // 将列内第0-2行的元素替换为下一行的内容(实现上移)
        for (int row = 0; row < 3; ++row) {
            arr[row][col] = arr[row + 1][col];
        }
        // 将保存的元素放到当前列的最后一行
        arr[3][col] = tmp;
    }
}

int main()
{
    int arcg[4][4] = {{3, 7, 6, 5}, {5, 8, 2, 4}, {9, 7, 3, 1}, {8, 2, 1, 0}};

    cycleup(arcg);
    for (int row = 0; row < 4; ++row) {
        for (int col = 0; col < 4; ++col)
            cout << "\t" << arcg[row][col];
        cout << endl;
    }
}

两种方案运行后都能得到你预期的输出:

5	8	2	4
9	7	3	1
8	2	1	0
3	7	6	5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:47:48