public void plus() //相加,时间复杂度为O(n^2) { if (polyA == null) { Console.WriteLine("式子A还没有输入"); return; } if (polyB == null) { Console.WriteLine("式子B还没有输入"); return; } double co; double pow; poly[] pA = new poly[polyA.Length]; poly[] pB = new poly[polyB.Length]; DataStruct1.Copy(polyA, pA); DataStruct1.Copy(polyB, pB); poly[] plusr = new poly[polyA.Length + polyB.Length]; foreach (var p in pA) { foreach (var p1 in pB) { if (p.pow == p1.pow) //遍历两式查找相同的次数,相同加到A式,并且B式相同次数项作废 { p.co += p1.co; p1.co = 0; p1.pow = 0; } } } int i = 0; //位置 foreach (var p in pA) { co = p.co; pow = p.pow; plusr[i] = new poly(co, pow); i++; } foreach (var p in pB) { co = p.co; pow = p.pow; plusr[i] = new poly(co, pow); i++; } sort(plusr); show(plusr); }
public void der(poly[] p) { if (p == null) { Console.WriteLine("式子还没有输入"); return; } poly[] p1 = new poly[p.Length]; DataStruct1.Copy(p, p1); foreach (var temp in p1) { if (temp.pow == 0) { temp.co = 0; } if (temp.co != 0) { temp.co *= temp.pow; temp.pow -= 1; } } show(p1); }
static void Main(string[] args) { int select = 1; //选项 Root(); Calculator c = new Calculator(); //初始化计算器 a: try { select = int.Parse(Console.ReadLine()); if (select < 1 || select > 11) //检验选项正确性 { throw new ArgumentException("请输入正确的选项"); } } catch (Exception e) { Console.WriteLine(e.Message); Thread.Sleep(1500); Main(args); } switch (select) { case 1: Console.WriteLine("输入多项式A"); c.create(1); break; case 2: Console.WriteLine("输入多项式B"); c.create(2); break; case 3: Console.WriteLine("显示多项式A"); c.show(c.polyA); break; case 4: Console.WriteLine("显示多项式B"); c.show(c.polyB); break; case 5: Console.WriteLine("显示式A+式B结果"); c.plus(); break; case 6: Console.WriteLine("显示式A-式B结果"); if (c.polyA == null) { Console.WriteLine("式子A还没有输入"); break; } if (c.polyB == null) { Console.WriteLine("式子B还没有输入"); break; } poly[] pA = new poly[c.polyA.Length]; poly[] pB = new poly[c.polyB.Length]; DataStruct1.Copy(c.polyA, pA); DataStruct1.Copy(c.polyB, pB); c.minus(pA, pB); break; case 7: Console.WriteLine("显示式B-式A结果"); if (c.polyA == null) { Console.WriteLine("式子A还没有输入"); break; } if (c.polyB == null) { Console.WriteLine("式子B还没有输入"); break; } poly[] pA1 = new poly[c.polyA.Length]; poly[] pB1 = new poly[c.polyB.Length]; DataStruct1.Copy(c.polyA, pA1); DataStruct1.Copy(c.polyB, pB1); c.minus(pB1, pA1); break; case 8: Console.WriteLine("显示式A导数"); c.der(c.polyA); break; case 9: Console.WriteLine("显示式B导数"); c.der(c.polyB); break; case 10: Console.Write("输入X:"); try { double x = double.Parse(Console.ReadLine()); c.calX(c.polyA, x); }catch (Exception e) { Console.WriteLine(e.Message); } break; case 11: Console.Write("输入X:"); try { double x = double.Parse(Console.ReadLine()); c.calX(c.polyB, x); } catch (Exception e) { Console.WriteLine(e.Message); } break; } Console.WriteLine("输入(1-11)继续进行相应操作:"); goto a; }