对角线差异OutOfRange异常C#

时间:2016-06-05 11:31:57

标签: c# difference diagonal

我必须编写一个程序,找出家庭作业的方阵对角线总和之间的差异,但我的代码抛出了IndexOutOFRange异常,我不知道如何修复它。

以下源代码: //输入3 11 2 4 4 5 6 10 8 -12 //所需输出:15

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


    class diagonalDifference
    {
        static void Main()
        {

    int N = Convert.ToInt16(Console.ReadLine());
    int[,] arr = new int[N, N];
    string str = string.Empty;

    for (int i = 0; i < N; ++i)
    {
        string[] strArr = Console.ReadLine().Split(' ');
        for (int j = 0; j < strArr.Length; ++j)
        {
            arr[i, j] = Convert.ToInt16(strArr[j]);
        }
    }

    int left = 0, right = N - 1, ldTotal = 0, rdTotal = 0;
    while (left <= right)
    {


    ldTotal += arr[left, left];


    rdTotal += arr[left++, right];
    }    

    Console.WriteLine(Math.Abs(ldTotal - rdTotal));



     }
        }

2 个答案:

答案 0 :(得分:0)

 class diagonalDifference
    {
        static void Main()
        {

    int N = Convert.ToInt16(Console.ReadLine());
    int[,] arr = new int[N, N];
    string str = string.Empty;

    for (int i = 0; i < N; ++i)
    {
        string[] strArr = Console.ReadLine().Split(' ');
        for (int j = 0; j < strArr.Length; ++j)
        {
            arr[i, j] = Convert.ToInt16(strArr[j]);
        }
    }

    int left = 0, right = N - 1, ldTotal = 0, rdTotal = 0;
    while (left <= (N-1))
    {


    ldTotal += arr[left, left];


    rdTotal += arr[left, right];
Left++;
Right--;
    }    

    Console.WriteLine(Math.Abs(ldTotal - rdTotal));



     }
        }

答案 1 :(得分:0)

班级成绩 {

/*
 * Complete the 'diagonalDifference' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts 2D_INTEGER_ARRAY arr as parameter.
 */

public static int diagonalDifference(List<List<int>> arr)
{
    int l=arr.Count;
    int d1=0;
    int d2=0;
    for(int i=0;i<l;i++)
    {
    d1=d1+arr[i][i];
    d2=d2+arr[i][l-1-i];
    }
    return (Math.Abs(d1-d2));
}

}