算法问题.如何用c#实现多项式相加.

cxfcxf8 2008-02-20 11:06:53
最近想学习下关于算法的知识.可是看到例子大部分是c程序,如果用c#实现的话比较困难.不安全代码不太会,
用静态链表也不是很懂.向高手求助..
...全文
759 29 打赏 收藏 转发到动态 举报
写回复
用AI写文章
29 条回复
切换为时间正序
请发表友善的回复…
发表回复
小白大大-- 2012-10-24
  • 打赏
  • 举报
回复
来看看。。。
cxfcxf8 2008-02-26
  • 打赏
  • 举报
回复
非也,非也。只是练习下基础知识。最近发现学习这个数据结构有些帮助。
cxfcxf8 2008-02-25
  • 打赏
  • 举报
回复
看来大虾们提供的方法.我得仔细研究一阵子..
感谢啊.
今天我看到数据结构的树上提到了多项式的编程.其中涉及到变量不止一个.有x.y.z等等.进行多项式的算法.用的是广义表.这个就更麻烦了.
我还是先把这一个变量的搞清楚.
Q_282898034 2008-02-25
  • 打赏
  • 举报
回复
好像有高人说把表达式做成二叉树,然后前序遍历求解
dingkai19830 2008-02-25
  • 打赏
  • 举报
回复
上面的代码可以进行有括号的+-*/多项式运算,要加个乘方也是很容易的
dingkai19830 2008-02-25
  • 打赏
  • 举报
回复
乘方运算没有添加进去,可参照下面的

using System;
using System.Collections.Generic;
using System.Text;

namespace String_c
{
class string_c
{
public string_c()
{
}

private string lfrq(string str)
{
str = str.Replace("-", "+-");
str = str.Replace("++", "+");
str = str.Replace("*+", "*");
str = str.Replace("/+", "/");
while (str[0] == '+')
{
str = str.Substring(1);
}
return str;
}

public string 值计算(string str)
{
str = lfrq(str);
string str1, str2, str3, str4;
int index1, index2;
char cha;
int p = 0;
//取出括号内字符串计算
index1 = str.IndexOf('(');
if (index1 != -1)
{
index2 = 0;
for (int i = index1 + 1; i < str.Length; i++)
{
if (str[i] == '(') p++;
if (str[i] == ')')
{
if (p == 0) index2 = i;
else p--;
}
}
str1 = str.Substring(0, index1);
str2 = str.Substring(index1 + 1, index2 - index1 - 1);
str3 = str.Substring(index2 + 1);
str = str1 + 值计算(str2) + str3;
}
//取得运算符位置,优先乘除运算符
index1 =
(str.IndexOf('*') > 0 ? str.IndexOf('*') : 9999) <
(str.IndexOf('/') > 0 ? str.IndexOf('/') : 9999) ?
(str.IndexOf('*') > 0 ? str.IndexOf('*') : 9999) :
(str.IndexOf('/') > 0 ? str.IndexOf('/') : 9999);
if (index1 == 9999) index1 = str.IndexOf('+');
if (index1 == -1) return (str);
//取得运算符
cha = str[index1];
//取得运算符前一个数和后一个数及余下的字符串
str1 = str.Substring(0, index1);
str2 = str.Substring(index1 + 1, str.Length - 1 - index1);
index1 =
str1.LastIndexOf('*') > str1.LastIndexOf('/') ?
str1.LastIndexOf('8') : str1.LastIndexOf('/');
index1 =
str1.LastIndexOf('+') > index1 ?
str1.LastIndexOf('+') : index1;
str3 = str1.Substring(0, index1 + 1);
str1 = str1.Substring(index1 + 1, str1.Length - 1 - index1);
index1 = str2.IndexOf('*') > -1 ? str2.IndexOf('*') : 9999;
index2 = str2.IndexOf('/') > -1 ? str2.IndexOf('/') : 9999;
index1 = index1 < index2 ? index1 : index2;
index2 = str2.IndexOf('+') > -1 ? str2.IndexOf('+') : 9999;
index1 = index1 < index2 ? index1 : index2;
if (index1 == 9999)
{
str4 = str2;
str2 = "";
}
else
{
str4 = str2.Substring(0, index1);
str2 = str2.Substring(index1, str2.Length - index1);
}

//运算
double d1, d2;
str1 = str1.Replace("E", "E+");
str4 = str4.Replace("E", "E+");
if (str1[0] == '-') d1 = 0 - double.Parse(str1.Substring(1, str1.Length - 1));
else d1 = double.Parse(str1);
if (str4[0] == '-') d2 = 0 - double.Parse(str4.Substring(1, str4.Length - 1));
else d2 = double.Parse(str4);
switch (cha)
{
case '+':
d1 = d1 + d2;
break;
case '*':
d1 = d1 * d2;
break;
case '/':
d1 = d1 / d2;
break;
default:
break;
}
str = str3 + d1.ToString() + str2;
str = str.Replace("E+", "E");
index1 = str.IndexOf('+');
index1 =
str.IndexOf('*') > index1 ?
str.IndexOf('*') : index1;
index1 =
str.IndexOf('/') > index1 ?
str.IndexOf('/') : index1;
if (index1 == -1)
return str;
else
str = 值计算(str);

return str;
}
}
}
i0876 2008-02-25
  • 打赏
  • 举报
回复
你们要做导弹轨道运算?
cxfcxf8 2008-02-25
  • 打赏
  • 举报
回复

//c#静态链表节点的形式.
class ListNode
{
private object data;
private ListNode next;

public object Data
{
get { return data; }
set { data = value; }
}

public ListNode Next
{
get { return next; }
set { next = value; }
}

public ListNode(object dataValue, ListNode nextNode)
{
data = dataValue;
next = nextNode;
}

public ListNode(object dataValue)
: this(dataValue, null)
{
}
}
//链表方法.至于怎么用泛型.现在也不是很清楚.学习..
class List
{
private ListNode firstNode;
private ListNode lastNode;
private string name;

public List(string listName)
{
name = listName;
firstNode = lastNode = null;
}

public List()
: this("list")
{
}

public void InsertAtFront(object insertItem)
{
lock (this)
{
if (IsEmpty())
{
firstNode = lastNode = new ListNode(insertItem);
}
else
{
firstNode = new ListNode(insertItem, firstNode);
}
}
}

public void InsertAtBack(object insertItem)
{
lock (this)
{
if (IsEmpty())
{
firstNode = lastNode = new ListNode(insertItem);
}
else
{
lastNode = lastNode.Next = new ListNode(insertItem);
}
}
}

public object RemoveFromFront()
{
lock (this)
{
if (IsEmpty())
throw new EmptyListException(name);

object removeItem = firstNode.Data;

if (firstNode == lastNode)
{
firstNode = lastNode = null;
}
else
{
firstNode = firstNode.Next;
}

return removeItem;
}
}

public object RemoveFromBack()
{
lock (this)
{
if (IsEmpty())
throw new EmptyListException(name);

object removeItem = lastNode.Data;

if (firstNode == lastNode)
{
firstNode = lastNode = null;
}
else
{
ListNode currentNode = firstNode;

while (currentNode.Next != lastNode)
{
currentNode = currentNode.Next;
}

lastNode = currentNode;
currentNode.Next = null;
}

return removeItem;
}
}

public bool IsEmpty()
{
lock (this)
{
return firstNode == null;
}
}

public void Print()
{
lock (this)
{
if (IsEmpty())
{
Console.WriteLine("Empty " + name);
return;
}

Console.WriteLine("The " + name + " is: ");

ListNode currentNode = firstNode;

while (currentNode != null)
{
Console.WriteLine(currentNode.Data + " ");
currentNode = currentNode.Next;
}

Console.WriteLine("\n");
}
}

public void Find(object data)
{
lock (this)
{
ListNode currentNode = firstNode;

while (currentNode != null)
{
if (currentNode.Data == data)
{
Console.WriteLine("find {0}", data);
return;
}
else
{
currentNode = currentNode.Next;
}
}
Console.WriteLine("{0} not found", data);
}
}

public void Del(object Data)
{
lock (this)
{
if (IsEmpty())
{
Console.WriteLine("链表为空");
return;
}
else
{
ListNode currentNode = firstNode;
while (currentNode != null)
{
if (currentNode.Data == Data)
{
currentNode.Next = currentNode.Next;
return;
}
else
{
currentNode = currentNode.Next;
}
}
Console.WriteLine("{0},is deleted", Data);
}
}
}
}


ProjectDD 2008-02-25
  • 打赏
  • 举报
回复
这儿来个网上搜到的,已经成功通过本人的检验.(与原代码相比小有改变)

// using System;
namespace Polyn
{
public class Polynominal
{
int HighPower;//多项式的次数
double[] CoeffArray = new double[100];//数组用来存储多项式的系数,数组的项次表示多项式的次数
//olynominal p; =new Polynominal();
public Polynominal() //构造函数,初始化。
{
HighPower = 0;
int i;
for (i = 0; i < CoeffArray.Length; i++)
CoeffArray[i] = 0;
}

public Polynominal(int Exponent) //为了在测试时减少每次输入的麻烦,故设此构造函数。
{
HighPower = Exponent;
int i;
int t;
for (i = 0, t = 1; i <= Exponent; i++, t++)
{
CoeffArray[i] = t * t;
}
}
/// <summary>
/// 读入多项式的系数和次数
/// </summary>
public void ReadIn() //读入多项式的系数和次数
{
int Exponent;//次数
double Coefficient;
Console.WriteLine("当系数输入为0时表示多项式输入完毕.");
while (true) //确保输入的数据有效
{
Console.WriteLine("读入多项式的最高次数:");
if (!(int.TryParse(Console.ReadLine(), out HighPower)))
{
Console.WriteLine(" 输入的不是整数,请重新输入");
continue;
}
else
break;
}

while (true)
{
Console.WriteLine("输入某一项的次数(int型):");
if (!(int.TryParse(Console.ReadLine(), out Exponent)))
{
Console.WriteLine("不是整数,请重新输入:");
continue; //确保输入的“次”符合要求
}
else if (Exponent > HighPower)
{
Console.WriteLine("该项次数大于多项式的最高次数,请重新输入:");
continue;
}
Console.WriteLine("输入系数(浮点型):");

while (true)
{
if (!(double.TryParse(Console.ReadLine(), out Coefficient)))
{
Console.WriteLine("输入的不是实数,请重新输入");
continue;
}
break;
}
if (Coefficient == 0) //退出条件,当系数为零时退出
break;
CoeffArray[Exponent] = Coefficient;
}
}
/// <summary>
/// 输出多项式,系数为零的不输出.
/// </summary>
public void PrintPoly() //输出多项式,系数为零的不输出.
{
int i = 0;
Console.WriteLine();
Console.WriteLine("输出多项式:");
Console.Write("Poly:=");
while (CoeffArray[i] == 0) //寻找第一个系数不为零的项
{
i++;
}

if (i != 0 && i != 1) //当第一个系数不为零的项是次数为零 或为1的项需要作特殊处理。不能在输出结果中出现形如12X^0+1X^1的形式,正确表达应为12+x
{
Console.Write("{0}X^{1}", CoeffArray[i], i);

}
else if (i == 0)
{
Console.Write("{0}", CoeffArray[i]);
i++;
if (CoeffArray[i] != 1)
Console.Write("+{0}X", CoeffArray[i]);
else
Console.Write("+X");
}
else if (CoeffArray[i] != 1)
Console.Write("{0}X", CoeffArray[i]);
else
Console.Write("X");
i++;
while (i < CoeffArray.Length)
{
if (CoeffArray[i] != 0)
Console.Write("+{0}X^{1}", CoeffArray[i], i);
i++;
}
}

private int Max(int t1, int t2) //求两个数中的最大值
{
return (t1 > t2 ? t1 : t2);
}
/// <summary>
/// 多项式相加
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
void AddPoly(Polynominal p1, Polynominal p2) //多项式的相加
{
//p=new Polynominal();
int i;
HighPower = Max(p1.HighPower, p2.HighPower);
for (i = 0; i < this.HighPower; i++)
{
CoeffArray[i] = p1.CoeffArray[i] + p2.CoeffArray[i];
}

}

public static Polynominal operator +(Polynominal p1, Polynominal p2) //重载"+"操作符。
{
Polynominal p = new Polynominal();
p.AddPoly(p1, p2);
return p;
}

void MultiPoly(Polynominal p1, Polynominal p2) //多项式相乘
{
int i, j;
HighPower = p1.HighPower + p2.HighPower;
if (HighPower > 1000)
{
Console.WriteLine("超出存储范围");
}
else
{
for (i = 0; i <= p1.HighPower; i++)
for (j = 0; j <= p2.HighPower; j++)
CoeffArray[i + j] += p1.CoeffArray[i] * p2.CoeffArray[j];
}

}

public static Polynominal operator *(Polynominal p1, Polynominal p2) //重载"*"操作符。
{
Polynominal p = new Polynominal();
p.MultiPoly(p1, p2);
return p;
}
}
}
wudi626 2008-02-24
  • 打赏
  • 举报
回复
关注,学习
ProjectDD 2008-02-24
  • 打赏
  • 举报
回复
下一步可以考虑在17楼的基础上进行一些优化或修饰.
zlz_212 2008-02-22
  • 打赏
  • 举报
回复
波兰表达式,逆波兰表达式,堆栈
harryheart 2008-02-22
  • 打赏
  • 举报
回复
要下班了,只能写个很简陋的,不过大概的思路不会错的
输出:2*x^0+4*x^1+2*x^2+2*x^3+2*x^5+
格式比较丑陋,楼主可以自己再控制一下输出

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
//新建一个表达式和一些新项,并向表达式中插入这些项
MyExpression me = new MyExpression();

MyItem item1 = new MyItem(2, 0);
MyItem item2 = new MyItem(2, 3);
MyItem item3 = new MyItem(2, 1);
MyItem item4 = new MyItem(2, 5);
MyItem item5 = new MyItem(2, 2);

me.InsertItem(item1);
me.InsertItem(item2);
me.InsertItem(item3);
me.InsertItem(item3);
me.InsertItem(item4);
me.InsertItem(item5);

foreach (MyItem mi in me.Expression)
{
Console.Write(mi.Num + "*x^" + mi.Exp + "+");
}
Console.ReadKey();
}
}

/// <summary>
/// 表达式类,用于存储所有的项
/// </summary>
class MyExpression
{
private List<MyItem> _expression;//用于存储表达式的项
internal List<MyItem> Expression
{
get { return _expression; }
set { _expression = value; }
}
/// <summary>
/// 初始化一个表达式
/// </summary>
public MyExpression()
{
Expression = new List<MyItem>();
MyItem item = new MyItem(0, 0);
Expression.Add(item);
}

/// <summary>
/// 插入一个项,根据指数来确定插入新项还是与原有项相加
/// </summary>
/// <param name="item"></param>
public void InsertItem(MyItem item)
{
int length = Expression.Count;
bool hasInserted = false;
for (int i = 0; i < length; i++)
{
if (Expression[i] > item) //当前项指数比插入项大时,插到当前项的位置
{
Expression.Insert(i, item);
hasInserted = true;
break;
}
if (Expression[i].Exp == item.Exp)//指数相等时相加
{
Expression[i].Num += item.Num;
hasInserted = true;
break;
}
}
if (!hasInserted)
{
Expression.Add(item);//指数比已知项都要大,插到表达式尾部
}
}

protected void Sort()
{
this.Expression.Sort();
}
}

/// <summary>
/// 结点类,存储每一项
/// </summary>
class MyItem : IComparable<MyItem>
{
private int _num;//倍娄
public int Num
{
get { return _num; }
set { _num = value; }
}

private int _exp;//指数
public int Exp
{
get { return _exp; }
set { _exp = value; }
}
/// <summary>
/// 给定值构造一个新项
/// </summary>
/// <param name="num"></param>
/// <param name="exp"></param>
public MyItem(int num, int exp)
{
Num = num;
Exp = exp;
}

public bool Compare(MyItem left, MyItem right)
{
if (left.Exp > right.Exp)
{
return true;
}
else
return false;
}

public int CompareTo(MyItem item)
{
return this.Exp.CompareTo(item.Exp);
}

public static bool operator >(MyItem left, MyItem right)
{
return left.Exp.CompareTo(right.Exp) > 0;
}

public static bool operator <(MyItem left, MyItem right)
{
return left.Exp.CompareTo(right.Exp) > 0;
}

//public object Clone()
//{
// return new MyItem(this.Num,this.Exp);
//}
}
}

cxfcxf8 2008-02-22
  • 打赏
  • 举报
回复
没帮的了吗 ??
cxfcxf8 2008-02-21
  • 打赏
  • 举报
回复
具体算法已经很清楚了.就是不知道怎么实现..
首先建两个有序链表.
然后对两个链表进行合并.合成一个链表.如果幂相同的就加.不相同的按照幂的大小接如合并的链表.
就是不知道如何实现??
qshzf 2008-02-21
  • 打赏
  • 举报
回复
关注
cxfcxf8 2008-02-21
  • 打赏
  • 举报
回复
主要是想学习链表操作(c语言里边这个指针用比较好用)到了c#我发现不太好写.
如果是数组之类的.也会些.
主要是想用c#实现链表操作.建链表.对链表进行操作...不太会.大部分例子都是c语言的.
wanghui0380 2008-02-21
  • 打赏
  • 举报
回复
呵呵,说的挺玄乎,实际上就是矩阵操作,c#下有很完整的矩阵操作类啊

harryheart 2008-02-21
  • 打赏
  • 举报
回复
算法应该不是很难吧?把幂指数相同的项加起来就可以了
比较繁琐的地方应该是把表达式有序的封装成数组或者链表,不过也只是繁琐而已
lake_cx 2008-02-21
  • 打赏
  • 举报
回复
照楼上那么看,不就是数组按位累加?
加载更多回复(9)

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧