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

如何修复代码使GetSumOfElementsFromTheMainDiagonal适配任意大小方阵?

修复方阵主对角线求和函数以支持任意大小方阵

错误原因

C++中,二维数组作为函数参数传递时会退化为指向数组首元素的指针。你的函数参数int a[][MAX_SIZE]实际等价于int (*a)[MAX_SIZE](指向含50个int的数组的指针),但你传入的int[3][3]会退化为int(*)[3],这两种指针类型不兼容,因此编译器报错。

修复方案

方案1:模板函数(推荐,类型安全)

利用模板让编译器自动推导方阵的大小,同时确保传入的是行、列尺寸一致的方阵:

#include <iostream>

using namespace std;

template <size_t N>
int GetSumOfElementsFromTheMainDiagonal(int (&a)[N][N])
{
    int sum = 0;
    for (size_t i = 0; i < N; ++i)
    {
        sum += a[i][i];
    }
    return sum;
}

int main()
{
    int a[3][3] = {
        {1, 2, 3},
        {2, 3, 5},
        {7, 7, 7}
    };

    int b[5][5] = {
        {1,0,0,0,0},
        {0,2,0,0,0},
        {0,0,3,0,0},
        {0,0,0,4,0},
        {0,0,0,0,5}
    };

    cout << GetSumOfElementsFromTheMainDiagonal(a) << endl; // 输出11
    cout << GetSumOfElementsFromTheMainDiagonal(b) << endl; // 输出15
}

方案2:一维数组模拟二维数组

将二维方阵转为一维数组传递,手动计算主对角线元素的索引:

#include <iostream>

using namespace std;

int GetSumOfElementsFromTheMainDiagonal(int* a, int n)
{
    int sum = 0;
    for (int i = 0; i < n; ++i)
    {
        sum += a[i * n + i]; // 主对角线元素的一维索引为i*n + i
    }
    return sum;
}

int main()
{
    int a[3][3] = {
        {1, 2, 3},
        {2, 3, 5},
        {7, 7, 7}
    };

    cout << GetSumOfElementsFromTheMainDiagonal(&a[0][0], 3) << endl; // 输出11
}

方案3:使用vector容器(现代C++风格)

用vector<vector<int>>存储方阵,函数直接接收该容器,还能额外做方阵合法性检查:

#include <iostream>
#include <vector>

using namespace std;

int GetSumOfElementsFromTheMainDiagonal(const vector<vector<int>>& a)
{
    int sum = 0;
    // 检查是否为合法方阵
    if (a.empty() || a.size() != a[0].size())
    {
        cerr << "输入不是有效方阵" << endl;
        return 0;
    }

    int n = a.size();
    for (int i = 0; i < n; ++i)
    {
        sum += a[i][i];
    }
    return sum;
}

int main()
{
    vector<vector<int>> a = {
        {1, 2, 3},
        {2, 3, 5},
        {7, 7, 7}
    };

    vector<vector<int>> b = {
        {10,20},
        {30,40}
    };

    cout << GetSumOfElementsFromTheMainDiagonal(a) << endl; // 输出11
    cout << GetSumOfElementsFromTheMainDiagonal(b) << endl; // 输出50
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:56:12