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

二维数组行和与列和计算异常求助:列求和结果始终为0

解决二维数组列求和始终为0的问题

嘿,我看出来你踩了两个小坑啦!咱们一步步把问题捋清楚:

问题1:列求和的数组下标搞反了

在你的内部循环里,列求和的代码写的是:

vertical[c]=vertical[c]+characters[c][r];

但你当前遍历的是第r行第c列的元素characters[r][c],要计算第c列的总和,应该累加这个元素才对,而characters[c][r]指的是第c行第r列的元素,完全不是你要的列元素,这就导致列和根本没被正确累加。

问题2:输出列和时访问了数组越界位置

当内部循环(c的循环)结束时,c的值已经等于rc了(因为循环条件是c < rc,最后一次循环执行完后c会自增到rc),这时候你输出vertical[c],访问的是数组的越界位置——刚好这个位置的内存值是0,所以每次都输出0。

修正后的代码

我调整了代码逻辑,把列和的输出移到了所有矩阵遍历完成后,同时修正了下标错误:

#include <iostream>
using namespace std;
int main() {
    int characters[50][50], rc, sum = 0, horizontal[10] = {0}, vertical[10] = {0}, c, r;
    cout << "Please enter integer : ";
    cin >> rc;
    cout << " The matrix is : \n";
    
    // 先填充矩阵,计算行和与列和
    for(r = 0; r < rc; r++){
        for(c = 0; c < rc; c++){
            sum += 1;
            characters[r][c] = sum;
            cout << characters[r][c] << " ";
            horizontal[r] += characters[r][c];
            // 修正:累加当前行r、列c的元素到列c的总和中
            vertical[c] += characters[r][c];
        }
        // 只输出当前行的行和
        cout << " | The sum of horizontal is = " << horizontal[r];
        cout << endl;
    }
    
    // 单独输出所有列的和,避免下标越界
    cout << "\nThe sum of each vertical column: ";
    for(c = 0; c < rc; c++){
        cout << vertical[c] << " ";
    }
    cout << endl;
    
    return 0;
}

测试运行结果

当输入3时,输出会变成:

Please enter integer : 3
 The matrix is : 
1 2 3  | The sum of horizontal is = 6
4 5 6  | The sum of horizontal is = 15
7 8 9  | The sum of horizontal is = 24

The sum of each vertical column: 12 15 18 

这样行和与列和就都正确啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:54:08