我的作业有问题,要求我让编译器打印出一个矩阵,其中所有对角线都输出为零。我还必须将它传递给一个函数。但是,我不知道该怎么做..
这是我的代码:
#include <iostream>
using namespace std;
int diagonals();
int main()
{
//problem 1
int matrix[3][3];
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3 ; j++)
{
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << "\nReverse of the matrix:" << endl;
for (int j = 1; j <= 3; j++)
{
for (int i = 1; i <= 3; i++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}//end of problem 1
//problem 2
cout << "Diagonals changed to 0:\n" << endl;
}
答案 0 :(得分:0)
你的矩阵声明说int matrix[3][3];
它有三个1-D阵列&amp;在每个1-D阵列中,您可以存储三个元素。在C/C++
数组索引从zero
开始。
有问题的陈述是for (int i = 1; i <= 3; i++)
,因为您正在跳过matrix[0][0]
并试图存储到matrix[3][3]
,而0
不存在,这反过来会导致未定义行为
首先开始迭代从rows
到for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 ; j++) {
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
&amp;的循环。分别为。
row
要完成你提到的任务,打印出一个矩阵,其中所有对角线都输出为零。 ?写一个条件,以便col
值{&}; zero
值相等,然后将其分配给int main(void) {
int matrix[3][3] = { 0 }; /* initialize it */
int row = sizeof(matrix)/sizeof(matrix[0]); /* find no of rows */
int col = sizeof(matrix[0])/sizeof(matrix[0][0]);/* find no of columns */
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if( i == j)
matrix[i][j] = 0;/* when i and j are equal means thats diagonal and assign it to zero */
else /* if its not diagonal then scan from user */
std::cin>>matrix[i][j];
}
}
return 0;
}
,否则从用户扫描。这是示例代码
void diagonal(int (*mat)[3],int row, int col) { /* mat is pointer to an array */
std::cout<<"printing matrix "<<std::endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
std::cout<<mat[i][j]<<"\t";
}
std::cout<<std::endl;
}
}
其次,我还必须将它传递给函数。为此学习如何将2d数组传递给函数。以下是示例示例。
diagonal()
从main()
函数
diagonal(matrix,row,col); /* pass matrix, no of rows, no of columns */
,如下所示
div