IndexOutOfRange测试期间的异常 [英] IndexOutOfRange Exception during testing

查看:87
本文介绍了IndexOutOfRange测试期间的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下函数计算矩阵行列式:



I'm calculating matrix Determinant using the following function:

public static double matrixDeterminant(double[,] matrix)
{
    double sum = 0;
    int s;
    if (matrix.GetLength(0) == 1)
    {
        return (matrix[0, 0]);
    }
    for (int i = 0; i < matrix.GetLength(0); i++)
    {
        double[,] smallermatrix = new double[matrix.GetLength(0) - 1, matrix.GetLength(0) - 1];
        for (int a = 0; a < matrix.GetLength(0); a++)
        {
            for (int b = 0; b < matrix.GetLength(0); b++)
            {
                if (b<i)
                {
                    smallermatrix[a - 1, b] = matrix[a, b];

                }
                else if (b>i)
                {
                    smallermatrix[a - 1, b - 1] = matrix[a, b];

                }

            }

        }
        if (i % 2 == 0)
        {
            s = 1;
        }
        else s = -1;
        sum += s * matrix[0, i] * (matrixDeterminant(smallermatrix));

    }
    return sum;
}





当我用数组测试我的函数时



when I'm testing my function with an array

double[,] key = { { 1, 2 }, { 4, -5} };



我正在获得InedxOutOfRange!


I'm getting InedxOutOfRange!

else if (b>i)
                {
                    smallermatrix[a - 1, b - 1] = matrix[a, b];

                }



为什么?


Why?

推荐答案

我可以立即看到一个错误:你使用 matrix.GetLength(0)并且永远不要使用 matrix.GetLength(1)。这样,你永远不会考虑第二个索引的有效值集,因为它仍然未知。



修复此错误并查看测试是否通过。如果没有,请使用调试器来检测其他可能的问题。



让我采取有根据的猜测:你确实有其他一些错误,因为我报告的错误不可能是用数组 [x,x] 表示。但首先,修复我发现的错误。



另外,准确编写代码。正好两次调用 GetLength ,从不重复调用,使用堆栈变量来存储这些长度。避免使用单字母ID。等等...



-SA
One bug I can see immediately: you use matrix.GetLength(0) and never use matrix.GetLength(1). This way, you never take into account the valid set of values for the second index, because it remains unknown.

Fix this bug and see if the test passes. If not, use the debugger to detect other possible issues.

Let me take an educated guess: you do have some other bugs, because the bug I reported could not be manifested with the array [x,x]. But first, fix the bug I found.

Also, write your code accurately. Call GetLength exactly two times, never repeat the call, use the stack variable to store those length. Avoid single-letter IDs. And so on…

—SA


这篇关于IndexOutOfRange测试期间的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆