gpt4 book ai didi

c# - 多项式除法

转载 作者:行者123 更新时间:2023-11-30 16:04:15 29 4
gpt4 key购买 nike

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

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

关于c# - 多项式除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35285455/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com