c - 二维数组中对角线的总和

标签 c arrays

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);

[0,0]开始,到[8,8]结束

"Sum the diagonal values inside the 8x8 array starting at [0,0]"

我意识到我可以做一个 for 循环,因为形状只是 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

对于非方阵,如果你想对行数和列数相等的位置上的元素求和,可以这样做:

sum = 0
for i = 0 to min(rowcount,colcount)
  sum += matrix[i][i]
end-for
print sum

关于c - 二维数组中对角线的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5164911/

相关文章:

c - 读取 Zend 引擎 API 代码 : What does ## (double hash) mean?

在 C 中使用嵌套循环将 for() 循环转换为 do{}while

c - 在 C 中将数组作为参数传递

java - 访问 arraylist 数组中的元素

javascript - JavaScript 中的 JSON 行提取问题

java - 为什么C和Java代码之间的socket通信只收到64K数据?

c - 定义一个简单的整数数组

python - 使用 NumPy 将 ubyte [0, 255] 数组转换为 float 组 [-0.5, +0.5] 的最快方法

javascript - 从数组中选择随机项并将其删除,数组为空后重新启动

ios - 如何将新数据附加到现有的 JSON 数组 (swiftyJSON)