void ArrayDiagonal(double Array[4][4])
{
//declare local variables//
int i,j=0;
double dSum = 0;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(i==j)
{
dSum=dSum+Array[i][j];
}
}
}
printf("The sum of the main diagonal elements is = %.2f\n", dSum);
OffArrayDiagonal(Array);
}
void OffArrayDiagonal(double Array[4][4])
{
//declare local variables//
int i,j=0;
double dOff= 0;
for(i=0;i<4;i++)
{
for(j=4;j=0;j++)
{
if(i==j)
{
dOff=dOff+Array[i][j];
}
}
}
printf("The sum of the off diagonal elemets is = %.2f\n", dOff);
}
因此,对于我正在做的项目,我必须将数组的对角元素添加在一起。第一个功能正常工作,但我无法让其他方向正常工作。有什么想法吗?
最佳答案
一个问题是j
从 4 开始,然后递增(增加)到 5、6... 您还想从 3 而不是 4 开始。并且您不想将任何内容分配给 j
在有条件的情况下。所以使用 for(j=3;j>=0;j--)
.
不过,您实际上并不需要二维迭代,因为对角线是一维的。因此,一个更简单、更有效的解决方案是
for (i = 0 ; i < 4 ; i++)
dOff += Array[i][3-i];
第一条对角线也是如此。
关于c - 在c中对二维数组求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36366254/