简体   繁体   English

如何从对角线上获得数字总和?

[英]How can I get the sum of numbers from a diagonal line?

Here is the sum for a diagonal top-left to bottom-right: 这是从左上到右下的对角线的总和:

public int sumarDiagonal()
{
    int x = 0;
    for (int F = 0; F < Filas; F++)
    {
        for (int c = 0; c < Columnas; c++)
        {
            if (F == c)
            {
                x += m[F,c];
            }
        }
    }
    return x;
}

How can I go from top-right to bottom-left? 如何从右上角转到左下角?

Your original code with two nested loops is not very efficient. 您的带有两个嵌套循环的原始代码效率不是很高。 Better do it like this: 最好这样做:

public int sumarDiagonal() 
{ 
 int x = 0; 
 for (int i = 0; i < Math.Min(Filas,Columnas); ++i) 
  x += m[i,i]; 
 return x; 
} 

public int sumarAntiDiagonal() 
{ 
 int x = 0; 
 for (int i = 0; i < Math.Min(Filas,Columnas); ++i) 
  x += m[Filas - 1 - i,i]; 
 return x; 
} 

You don't actually need to look at every coefficient : 您实际上不需要查看每个系数:

public int sumarDiagonal()
    {
        int x = 0;
        int length = Math.Min(Filas,Columnas); // Can deal with rectangular cases
        for (int i = 0; i < length; i++)
            x += m[i,length-1-i];
        return x;
    }

Just reverse your indexes, like this: 只需反转索引,如下所示:

public int sumarDiagonal()
{
   int x = 0;
   for (int F = 0; F < Filas; F++)
   {
      x += m[F,Filas-F-1];
   }
   return x;
}

This assumes a square array, so for say 10x10, the first point is [0, 9], the second [1, 8], etc. 这假设一个正方形数组,因此对于10x10,第一个点是[0,9],第二个点[1,8],依此类推。

How about replacing 如何更换

if (F == c)

with

if (F + c + 1 == Filas)

Edit: Updated to account for 0-based array 编辑:更新以解决基于0的数组

   public int diagX()
        {
            int x;
            x = 0;

        for (f = 1; f <= filas; f++)
          {
           for (c = columnas; c >= 1; c--)
               {
                   if (f > c || f < c)
                   {
                       x += a[f, c];
                   }
                   else
                   {
                       continue;
                   }
                }
          }
        return x;
        }

for example this code : if you have 1 , 2 3 , 6 and you want to across diag you must take a[2, 1] you will get 2. and at the looping you've give continue on the else because after get value 2. it will be a[2, 2] because f == c as false then you break not come back to first loop. 例如下面的代码:如果您有1,2 3,6,并且您想遍历诊断,则必须取a [2,1]您将得到2。在循环中,您给出else继续,因为在获得价值之后2.这将是a [2,2],因为f == c为false,那么您中断就不会回到第一个循环。 why f==c is false because if you want search across diag of matrix you cant get value from f == c. 为什么f == c为假,因为如果您要搜索矩阵的对角线,则无法从f == c获得值。 for example: if matrix above we loop but can equals f and c. 例如:如果上面的矩阵我们循环,但可以等于f和c。 we can get: (a[2, 1] = 2) + (a[2, 2] = 6) = 8 nah! 我们可以得到:(a [2,1] = 2)+(a [2,2] = 6)= 8不! you can see the big false at this code. 您可以在此代码中看到很大的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM