21xrx.com
2025-06-22 01:00:08 Sunday
文章检索 我的文章 写文章
使用C++生成全1矩阵
2023-07-11 02:23:23 深夜i     46     0
C++ 全1矩阵 生成

在C++中生成全1矩阵是一个非常简单的任务,只需要使用nested for循环来填充每个元素为1即可。以下是一个例子:

#include <iostream>
int main() {
  int n;
  std::cout << "Enter the size of the matrix: ";
  std::cin >> n;
  int matrix[n][n];
  for(int i=0; i<n; i++) {
    for(int j=0; j<n; j++) {
      matrix[i][j] = 1;
    }
  }
  std::cout << "The matrix is:\n";
  for(int i=0; i<n; i++) {
    for(int j=0; j<n; j++) {
      std::cout << matrix[i][j] << " ";
    }
    std::cout << "\n";
  }
  return 0;
}

首先,我们从用户输入矩阵的大小开始。在这个例子中,我们使用变量n表示矩阵的大小。

接下来,我们定义一个n x n的数组matrix来存储矩阵。使用for循环遍历数组的每个元素,并将其赋值为1。

最后,我们使用一个for循环来打印出生成的矩阵。

此代码生成一个全1矩阵,输出如下:

Enter the size of the matrix: 4
The matrix is:
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

总之,使用C++生成全1矩阵非常简单。只需使用nested for循环将每个元素赋为1即可。

  
  

评论区