我正在编写一个程序来计算多项式的运算,并且我已经完成了其他运算(+ - *),但仍坚持除法,我总是在代码中看到此错误

static int[] DividePolnomials(int[] pol1, int[] pol2)
{
    int tmp = 0;
    int power_tmp = 0;
    int[] result_tmp;
    int[] result;
    if (pol1.Length > pol2.Length)
    {
        result = new int [pol1.Length];
        result_tmp = new int[pol1.Length];
        for (int i = 0; pol2.Length<=pol1.Length; i++)
        {

            if (pol2[pol2.Length-i-1] == 0) // here is the problem it gives that the index is outside the bounds
            {
                continue;
            }
            else
            {
                tmp = pol1[pol1.Length - i - 1] / pol2[pol2.Length - i - 1];
                power_tmp = (pol1.Length - i - 1) - (pol2.Length - i - 1);
                result[power_tmp] = tmp;
                result_tmp = Multiply(result, pol2);
                pol1 = SubtractPolnomial(pol1, result_tmp);
            }

        }
    }
    else
    {

        result = new int [pol1.Length];
    }
    return result;
}


由于此错误,我尚未完成代码中的所有其他方案,但是如果两个多项式的长度相等,我想获得任何帮助

最佳答案

您的i大于pol2.Length-1,因此,此时您具有pol2 [-1],pol2 [-2]等。C#中不允许这样做。您可以检查下一条语句:

       if ((pol2.Length-i-1 < 0) || (pol2[pol2.Length-i-1] == 0))
       {
           continue;
       }


编辑:如果第一个条件为真,则将不评估第二个条件
https://msdn.microsoft.com/en-us/library/6373h346.aspx

09-27 17:33