>我试图取 4x4 数组中所有对角线数的乘积。我知道如何抓住数字并打印它们,但我不确定如何取它们的乘积,我如何让它计算 8 个数字的乘积?
#include <iostream>
using namespace std;
for (int row = 0; row < 4; row++)
{
for (int column = 0; column < 4; column++)
{
if (row==column || row == 3 - column)
{
double product = 1;
product *= arr[row][column]
cout << product << ".";
}
}
}
注意:
- 只有
7
对角线元素。您将矩阵中心的元素计数两次。 - 您无需迭代整个数组即可了解对角线。正如您所观察到的,对角线具有很好的
row == column
属性,您只需要沿着对角线迭代。
为了使事情更清晰、更容易,请分别计算两个对角线乘积:
double product = 1;
for (int row = 0; row < 4; row++) {
product *= arr[row][row]
}
for (int row = 0; row < 4; row++) {
product *= arr[row][4 - (row + 1)]
}
如果您一次考虑每行中的两个条目,您还必须考虑中间元素出现在两个对角线中的事实,这使得代码不必要地混乱。
为什么要在循环中定义变量product
,这就是为什么存储在变量中的先前数据在超出范围时会丢失的原因。
#include <iostream>
using namespace std;
double product = 1; // var product should be defined out of the loop
for (int row = 0; row < 4; row++)
{
for (int column = 0; column < 4; column++)
{
if (row==column || row == 3 - column)
{
product *= arr[row][column];
}
}
}
cout << product << ".";