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

C++:如何利用动态二维向量计算文本矩阵各列和并输出内容与结果

解决方案:C++读取矩阵文件并计算任意列的列和

修改后的完整代码

#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>

using namespace std;

int main() {
    ifstream myfile("data.txt");

    if (!myfile.is_open()) {
        cout << "无法打开文件" << endl;
        system("pause");
        exit(0);
    }

    // 用二维动态向量存储整个矩阵
    vector<vector<float>> matrix;
    string line;

    cout << "文件内容:" << endl;
    while (getline(myfile, line)) {
        cout << line << endl;
        istringstream iss(line);
        vector<float> row;
        float num;
        // 读取当前行的所有数字,存入行向量
        while (iss >> num) {
            row.push_back(num);
        }
        if (!row.empty()) {
            matrix.push_back(row);
        }
    }

    if (matrix.empty()) {
        cout << "矩阵为空,无法计算列和" << endl;
        system("pause");
        return 0;
    }

    // 获取矩阵的列数(假设所有行的列数一致,同时兼容行长度不一致的情况)
    int col_count = 0;
    for (const auto& row : matrix) {
        if (row.size() > col_count) {
            col_count = row.size();
        }
    }
    vector<double> col_sums(col_count, 0.0);

    // 计算每一列的和
    for (const auto& row : matrix) {
        for (int col = 0; col < row.size(); ++col) {
            col_sums[col] += row[col];
        }
    }

    // 输出各列求和结果
    cout << "\n各列求和结果:" << endl;
    for (int i = 0; i < col_count; ++i) {
        cout << "第" << i+1 << "列和:" << fixed << setprecision(2) << col_sums[i] << endl;
    }

    system("pause");
    return 0;
}

关键修改说明

  • 二维向量存储矩阵:用vector<vector<float>> matrix替代原一维向量,完整保存整个矩阵的所有元素,天然适配任意行列数的矩阵。
  • 完整读取每行元素:读取每行时,将所有数字存入行向量再添加到二维矩阵中,不再仅提取第一个元素。
  • 动态适配列数:遍历所有行确定最大列数,即使矩阵行长度不一致也能正常计算列和。
  • 列和计算逻辑:遍历每行的每个元素,对应累加到列和向量的对应位置,避免数组越界问题。
  • 格式化输出:用fixed和setprecision保证求和结果的输出格式统一美观。

测试示例

假设data.txt内容如下:

1.5 2.3 3.7
4.1 5.9
7.2 8.4 9.6 10.0

运行程序后输出:

文件内容:
1.5 2.3 3.7
4.1 5.9
7.2 8.4 9.6 10.0

各列求和结果:
第1列和:12.80
第2列和:16.60
第3列和:13.30
第4列和:10.00

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:40:50