二维矩阵

时间:2010-04-30 15:35:54

标签: c++

找到二维矩阵的替代元素之和的逻辑。

3 个答案:

答案 0 :(得分:3)

//arr is the 2 D array MxN
int sum = 0;
for(int j=0;j<N;j++)
{
  for(int i=j&1;i<M;i+=2)
  {
      sum += a[i][j];
  }
}

答案 1 :(得分:2)

你可以将2D数组转换为1-D数组并在循环中进行求和。

int *a = (int*)arr; //arr being the 2 D array
int sum = 0;
for(int i=0;i<M*N;i+=2)
{
   sum += a[i];
}

答案 2 :(得分:0)

 for (int i = 0; i < N; ++ i)
   for (int j = i%2; j < M; j += 2) {
     std::cout << i << "," << j << std::endl;
     sum += a[i][j];
   }