【发布时间】:2024-04-26 04:55:01
【问题描述】:
所以我有一个 C++ 课程的作业。基本上我们必须创建一个 3x3 的多维数组,计算行和、列和、对角线值和对角线值和,我通常只输入 1 2 3 4 5 6 7 8 9 作为值作为开始点。
现在,我并不想无礼,但我的老师不是很好,我们基本上在一个问题上花费了 2 个小时,而她没有做太多解释。除此之外,我是从 C++ Primer and Programming: Principles and Practice Using C++ 开始的,所以我相信我自己能够学到很多东西。
无论如何,我的问题可能很愚蠢,但如果有人愿意提供帮助,他们就是:
- 我的 /**/ 为反对角值的循环注释给了我一个错误的总和。我假设它与 for 循环的性质有关,或者我只是输入错误,但我还没有弄明白。
2.老师计算对角线值的解法如下:
for (i = 0; i < row_num; ++i)
for (j = 0; j < col_num; ++j)
if (i + j == row_num - 1)
anti-diagonal += A[i][j];
它与我的方法有何不同?我相信我的更简单,效果更好。
3.排队:
int sumRows[row_num] = { 0 };
为什么必须使用 {}?我们的老师懒得解释。我尝试不使用 {},但出现错误。
这是我的版本的完整代码:
#include "../../std_lib_facilities.h"
#include <iostream>
using namespace std;
#define row_num 3 //no. of rows
#define col_num 3 //no. of columns
int main()
{
int i = 0;
int j = 0;
int diagonal = 0;
int antidiagonal = 0;
int sumRows[row_num] = { 0 };
int sumCol[col_num] = { 0 };
int A[row_num][col_num];
//Input to matrix
for(i=0; i<row_num; i++)
for (j = 0; j < col_num; j++)
{
cout << "A[" << i << "]" << "[" << j << "]: ";
cin >> A[i][j];
sumRows[i] += A[i][j];
sumCol[j] += A[i][j];
}
cout << endl;
//Print out the matrix
for (i = 0; i < row_num; i++)
{
for (j = 0; j < col_num; j++)
cout << A[i][j] << '\t';
cout << endl;
}
//prints sum of rows
for (i = 0; i < row_num; i++)
cout << "Sum of row " << i + 1 << " "<< sumRows[i] << endl;
//prints sum of columns
for (j = 0; j < row_num; j++)
cout << "Sum of column " << j + 1 << " " << sumCol[j] << endl;
//Sum of diagonal values
for (i = 0; i < row_num; i++)
diagonal += A[i][i];
//Sum of antidiagonal values
for (i = 0, j = 2; i < row_num, j >= 0; i++, j--)
antidiagonal += A[i][j];
/*for(i=0; i<row_num; i++)
for (j = 2; j >= 0; j--)
{
antidiagonal += A[i][j];
}
*/
cout << "\nSum of diagonal values: " << diagonal << endl;
cout << "Sum of antdiagonal values: " << antidiagonal << endl;
return 0;
}
【问题讨论】:
-
逗号不会像你想象的那样工作
-
用特定值填充数组是一种更简单的方法。 int sumRows[row_num] = { 0 };
-
你的教师循环更容易阅读和更正,你的不是(即使错误没有出现,但你的中断条件是错误的)
-
@tobi303 在这里一针见血。在可读性和良好/优雅的方法之间经常需要权衡。
标签: c++ for-loop multidimensional-array