for (row=0; row<SIZE; row++)
{
for (col=0; col<SIZE; col++)
{
if (row == 0 && col == 0) {
answer+=my_data[row][col];
}
else if ((row)/(col) == 1) //1 is slope of array
{
answer+=my_data[row][col];
}
}
}
printf("The diagonal sum of the 8x8 array is: %i\n",answer);
Run Code Online (Sandbox Code Playgroud)
从...开始到[0,0]
结束[8,8]
"从[0,0]开始,对8x8数组内的对角线值求和
我意识到我可以做一个单循环,因为形状只是1:1,但我怎么做才能以防万一我需要总结对角8x10数组?
对角线元素和主对角线仅针对方形矩阵定义.
if rowcount == colcount
sum = 0
for i = 0 to rowcount
sum += matrix[i][i]
end-for
else
print Diagonal sum not defined
end-if
Run Code Online (Sandbox Code Playgroud)
对于非方形矩阵,如果要将位置上的元素相等且行号和列号相等,则可以执行以下操作:
sum = 0
for i = 0 to min(rowcount,colcount)
sum += matrix[i][i]
end-for
print sum
Run Code Online (Sandbox Code Playgroud)