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

C++二维数组正弦波输出不符合预期问题求助

二维数组正弦波输出问题

要求将N×M的二维整数数组按正弦波顺序输出:第一列从上到下,第二列从下到上,依次交替。现有代码无法得到预期输出,测试用例示例为输入2×2数组{{5,6},{2,4}},预期输出应为5 2 6 4。

原代码存在的问题

  • 固定列数限制:函数wavePrint的参数int input[][2]硬编码了列数为2,无法处理任意列数的数组,通用性极差。
  • 数组越界访问:第一个循环结束后j的值等于nRows(测试用例中为2),此时访问input[j][i]会超出数组行下标范围(行下标最大为nRows-1)。
  • 循环逻辑漏洞:外层循环中手动执行i++,当总列数为奇数时,最后一列会被跳过;同时第二个循环的终止条件j>=0会重复输出下标0的元素,还会触发越界。

修正后的代码

动态数组版本(支持任意行列数)

#include <iostream>
using namespace std;

void wavePrint(int** input, int nRows, int mCols)
{
    for(int col = 0; col < mCols; col++){
        // 偶数列(从0开始计数)从上到下输出
        if(col % 2 == 0){
            for(int row = 0; row < nRows; row++){
                cout << input[row][col] << " ";
            }
        }
        // 奇数列从下到上输出
        else{
            for(int row = nRows - 1; row >= 0; row--){
                cout << input[row][col] << " ";
            }
        }
    }
}

int main()
{
    int nRows = 2, mCols = 2;
    // 动态分配二维数组
    int** input = new int*[nRows];
    for(int i = 0; i < nRows; i++){
        input[i] = new int[mCols];
    }
    input[0][0] = 5; input[0][1] = 6;
    input[1][0] = 2; input[1][1] = 4;
    
    wavePrint(input, nRows, mCols);
    cout << endl;
    
    // 释放内存
    for(int i = 0; i < nRows; i++){
        delete[] input[i];
    }
    delete[] input;
    
    return 0;
}

静态数组兼容版本(模板适配固定列数)

#include <iostream>
using namespace std;

template <int M>
void wavePrint(int input[][M], int nRows, int mCols)
{
    for(int col = 0; col < mCols; col++){
        if(col % 2 == 0){
            for(int row = 0; row < nRows; row++){
                cout << input[row][col] << " ";
            }
        } else {
            for(int row = nRows - 1; row >= 0; row--){
                cout << input[row][col] << " ";
            }
        }
    }
}

int main()
{
    int input[][2]={{5,6},{2,4}};
    wavePrint(input, 2, 2);
    cout << endl;
    return 0;
}

修正说明

  1. 参数通用性优化:动态数组版本支持任意行列数,模板版本适配不同列数的静态数组,摆脱了固定列数的限制。
  2. 循环逻辑简化:通过判断列的奇偶性决定遍历方向,无需手动修改外层循环变量,避免逻辑漏洞。
  3. 越界问题解决:倒序遍历从nRows-1开始,确保所有访问的下标都在合法范围内,不会出现重复输出或越界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:57:24