#include<iostream>
#include<conio.h>
using namespace std;
const int maxRows =3;
const int maxCols =3;
//prototype declaration
void readMatrix(int[][maxCols]);
void displayMatrix(int[][maxCols]);
//void displayFlippedMatrix(int [][maxCols]);
//
main(){
int a[maxRows][maxCols];
//read the matrix elements in array
readMatrix(a);
//display the original matrix
cout<<"\n\n"<<"the original matrix is: "<<'\n';
displayMatrix(a);
//display the flipped matrix
cout<<"\n\n"<<"the flipped matrix is :"<<'\n';
// displayFlippedMatrix(a);
getch();
system("pause");
}
void readMatrix(int a[][maxCols]){
int row,col;
for(row=0; row<maxRows; row++){
for(col=0; col<maxCols; col++){
cout<<"\n"<<"Enter"<<row<<","<<col<<"Element:";
cin>>a[row][col];
}
cout<<'\n';
}
}
// end of read Matrix........
void displayMatrix(int a[][maxCols]){
int row,col;
for(row=0; row<maxRows; row++){
for(col=0; col<maxCols; col++){
**cout<<a[0][1]<<'\t';**
}
cout<<'\n';
}
}
// end of displayMatrix......
/*
void displayFlippedMatrix(int a[][maxCols]){
int row,col;
for(row=maxRows-1; row>0; row--){
for(col=0; col<maxCols; col++){
cout<<a[row][col]<<'\t';
}
cout<<'\n';
}
}*/
这里我有完整的代码,从最后一行到最后一行翻转矩阵,第一行到最后一行,这段代码工作正常,但我有一个问题,我想了解它,如果任何一个我只想打印一个矩阵,即 cout&lt;&lt;&lt;&lt;&#;;&lt;&lt;&lt;&lt;&#;;&lt;&lt;&lt;&#;;&lt;&lt;&lt;&lt;&#;;&#39;&#39;知道[0] [1]零被称为第一行而[1]被称为第二列但它实际上是打印所有行和所有列,即使我只有cout [0] [1]第一行和第二列
答案 0 :(得分:1)
您只打印a[0][1]
,但是多次 。您打印相同的值maxRows * maxCols
次,因为它在嵌套循环中。
答案 1 :(得分:1)
在displayMatrix()
中,您的循环控制cout
命令执行的次数。因此,对于每a[0][1]
行,您基本上连续打印maxcols
maxrows
次。如果您的原始矩阵是这样的:
1 2 3
a[3][3] = 4 5 6
7 8 9
您的输出将是这样的:
2 2 2
2 2 2
2 2 2
要解决此问题,请对代码进行以下更改:
void displayMatrix(int a[][maxCols]){
int row,col;
cout<<"First row:\n";
for(col=0; col<maxCols; col++){
cout<<a[0][col]<<'\t';
}
cout<<"\n\nSecond column:\n";
for(row=0; row<maxRows; row++){
cout<<a[row][1]<<'\n';
}
}
输出看起来像这样:
First row:
1 2 3
Second Column:
2
5
8