21xrx.com
2025-04-07 04:34:00 Monday
文章检索 我的文章 写文章
C++实现矩阵输入的函数
2023-07-12 03:53:19 深夜i     32     0
C++ 矩阵 函数 输入

在C++中,矩阵是一种非常常见的数据结构。为了方便使用和操作矩阵,我们需要实现一个矩阵输入的函数。这个函数可以让用户输入一个矩阵,并将其存储在一个二维数组中。

以下是一个示例实现矩阵输入函数的代码:

#include <iostream>
using namespace std;
const int MAX_SIZE = 100; // 矩阵最大尺寸
// 定义一个结构体,表示矩阵
struct Matrix {
  int row; // 矩阵行数
  int col; // 矩阵列数
  int data[MAX_SIZE][MAX_SIZE]; // 存储矩阵数据的数组
};
// 用于输入矩阵的函数
Matrix inputMatrix() {
  Matrix mat;
  cout << "请输入矩阵行数和列数:" << endl;
  cin >> mat.row >> mat.col;
  cout << "请输入矩阵元素:" << endl;
  for (int i = 0; i < mat.row; ++i) {
    for (int j = 0; j < mat.col; ++j) {
      cin >> mat.data[i][j];
    }
  }
  return mat;
}
// 用于输出矩阵的函数
void outputMatrix(Matrix mat) {
  for (int i = 0; i < mat.row; ++i) {
    for (int j = 0; j < mat.col; ++j) {
      cout << mat.data[i][j] << " ";
    }
    cout << endl;
  }
}
int main() {
  Matrix mat = inputMatrix();
  outputMatrix(mat);
  return 0;
}

在上述代码中,我们使用了一个结构体`Matrix`来表示矩阵。结构体包含矩阵的行数、列数以及一个二维数组`data`,用于存储矩阵的具体数据。通过`inputMatrix`函数,我们可以让用户输入矩阵的行数、列数和具体数据,然后将它们存储在一个`Matrix`结构体对象中,并返回该对象。最后,我们使用`outputMatrix`函数可以输出该矩阵。

使用上述代码,我们可以方便地输入和输出矩阵。当然,如果需要在实际应用中使用该矩阵,我们还需要实现其他相关的函数,如矩阵加法、减法、乘法等。

  
  

评论区