数据结构与算法(C#实现)系列---演示篇(三)(转)

多项式运算C#实现
本文介绍了一种使用C#语言实现的多项式加法运算方法。通过SortedList存储多项式的系数与指数,并演示了两个多项式相加的过程。文章提供了完整的代码实现,包括初始化多项式、存储所有涉及的指数、进行加法操作并展示结果。
数据结构与算法(C#实现)系列---演示篇(三)

Heavenkiller(原创)

public static void ShowSortedList_Polynomial()

{

//100+10*x+x^2 + 1+10*x+100x^2

SortedList tmpListA=new SortedList();

SortedList tmpListB=new SortedList();

SortedList tmpListC=new SortedList();//used to store the result

SortedList tmpKeyList=new SortedList();//used to store all keys of two polynomials

//init polynomial A and show it

tmpListA.Add(0,100);

tmpListA.Add(1,10);

tmpListA.Add(2,1);

ShowSortedList_ShowPolynomial("tmpListA",tmpListA.GetEnumerator());

//init polynomial B and show it

tmpListB.Add(0,1);

tmpListB.Add(1,10);

tmpListB.Add(2,100);

ShowSortedList_ShowPolynomial("tmpListB",tmpListB.GetEnumerator());

//init the key list which contains all keys of A and B but everyone once

IDictionaryEnumerator tmpIDic=tmpListA.GetEnumerator();

while(tmpIDic.MoveNext()!=false)

{

if(!tmpKeyList.ContainsKey(tmpIDic.Key))

{

tmpKeyList.Add(tmpIDic.Key,null);

}

}

tmpIDic=tmpListB.GetEnumerator();

while(tmpIDic.MoveNext()!=false)

{

if(!tmpKeyList.ContainsKey(tmpIDic.Key))

{

tmpKeyList.Add(tmpIDic.Key,null);

}

}

//Add A and B and show the result

tmpIDic=tmpKeyList.GetEnumerator();

while(tmpIDic.MoveNext()!=false)

{

object objA=null,objB=null,objC=null;

objC=tmpIDic.Key;

if(tmpListA.ContainsKey(objC))

objA=tmpListA[objC];

if(tmpListA.ContainsKey(objC))

objB=tmpListB[objC];

//objC=objA+objB;

//tmpKeyList[objC]=(int)objA+(int)objC;

tmpListC.Add(objC,(int)objA+(int)objB);

}

ShowSortedList_ShowPolynomial("the addition result of A and B",tmpListC.GetEnumerator());

}

public static void ShowSortedList_ShowPolynomial(string tip,IDictionaryEnumerator iDic)

{

string strExpress=null;

iDic.Reset();

while(iDic.MoveNext()!=false)

{

strExpress+=iDic.Value.ToString()+"*X^"+iDic.Key.ToString()+"+";

}

Console.WriteLine(tip+":"+strExpress);

}

}

[@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/8781179/viewspace-924563/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/8781179/viewspace-924563/

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值