【问题标题】:Polynomial Division多项式除法
【发布时间】:2016-05-19 01:10:28
【问题描述】:

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

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;
}

由于这个错误,我还没有完成代码中的所有其他场景,但我希望在两个多项式长度相等的情况下获得任何帮助

【问题讨论】:

  • 你的意思是整数除法和余数吗?例如1 / (x + 1) 应该返回 0(并且 x + 1 应该是余数)
  • 我正在尝试应用长除法多项式,因为它在这里 purplemath.com/modules/polydiv2.htm

标签: c# arrays indexoutofboundsexception polynomials


【解决方案1】:

您的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

【讨论】:

    猜你喜欢
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    相关资源
    最近更新 更多