21xrx.com
2025-03-21 23:04:12 Friday
文章检索 我的文章 写文章
C++矩阵输入输出实现
2023-07-11 07:09:59 深夜i     15     0
C++ 矩阵 输入 输出 实现

实现矩阵输入输出是很常见的操作,本文将为大家分享一种实现方法。

首先我们需要定义一个矩阵类,该类包含矩阵的行数、列数和值。定义如下:

class Matrix {
public:
  Matrix(int rows, int cols);
  void setValue(int row, int col, double value);
  double getValue(int row, int col) const;
private:
  int rows, cols;
  double* values;
};

接下来我们实现矩阵输入和输出函数。输入函数从标准输入读取矩阵的行数、列数和每个元素的值。输出函数将矩阵以“行,列,值”格式输出到标准输出。代码如下:

void input(Matrix& matrix) {
  std::cin >> matrix.rows >> matrix.cols;
  matrix.values = new double[matrix.rows * matrix.cols];
  for (int i = 0; i < matrix.rows; i++) {
    for (int j = 0; j < matrix.cols; j++) {
      std::cin >> matrix.values[i*matrix.cols + j];
    }
  }
}
void output(const Matrix& matrix) {
  std::cout << matrix.rows << ' ' << matrix.cols << std::endl;
  for (int i = 0; i < matrix.rows; i++) {
    for (int j = 0; j < matrix.cols; j++) {
      std::cout << i << ' ' << j << ' ' << matrix.values[i*matrix.cols + j] << std::endl;
    }
  }
}

通过以上代码,我们就可以方便地输入和输出矩阵,使用时只需创建一个Matrix对象并调用input和output函数即可。

总的来说,矩阵操作是很常见的操作,掌握好矩阵输入输出实现方法,可以帮助我们更好地处理矩阵相关的问题。

  
  

评论区

请求出错了