用户输入一个矩阵,并且输出必须是一个新的矩阵,该矩阵具有一个附加的零列。如果将脚本应用于2平方矩阵,例如:{1,2,3,4}
,则新矩阵输出将为2行3列:{1,2,32,3,4,0}。我不明白数字32的输出。
#include <iostream>
int main(){
int m,n;
std::cout << "Input the size of the square matrix : ";
std::cin >> m;
n=m;
int A[m][n]={};
int M[m][n+1]={0};
for (int i(0);i<m;i++){
for(int j(0);j<n;j++){
std::cout << "Input element A["<<i<<"]["<<j<<"] : ";
std::cin >> A[i][j];
M[i][j]=A[i][j];
}
}
for (int i(0);i<m;i++){
for(int j(0);j<=n;j++){
std::cout << M[i][j] << " ";
}
std::cout << "\n";
}
return 0;
}
最佳答案
可变长度数组(VLA)是不可移植的gcc扩展,显然不会像您期望的那样初始化。
一种解决方案是使用std::vector
代替,它是可移植的,并且可以执行您想要的操作,如下所示:
#include <iostream>
#include <vector>
int main(){
int m,n;
std::cout << "Input the size of the square matrix : ";
std::cin >> m;
n=m;
std::vector <std::vector <int>> A;
std::vector <std::vector <int>> M;
A.resize (m);
M.resize (m);
for (int i = 0; i < m; ++i)
{
A [i].resize (n);
M [i].resize (n + 1);
}
for (int i(0);i<m;i++){
for(int j(0);j<n;j++){
std::cout << "Input element A["<<i<<"]["<<j<<"] : ";
std::cin >> A[i][j];
M[i][j]=A[i][j];
std::cout << "\n";
}
}
for (int i(0);i<m;i++){
for(int j(0);j<=n;j++){
std::cout << M[i][j] << " ";
}
std::cout << "\n";
}
}
Live demo
关于c++ - 复制矩阵的一部分并粘贴到另一个C++上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62220253/