一元多项式的建立及其运算
一元多项式的数据结构
#ifndef __POLYNOMIAL_H__
#define __POLYNOMIAL_H__
#include <bits/stdc++.h>
using namespace std;
typedef int DataType;
typedef struct node
{
double coef;
int exp;
struct node *link;
}Term, *Polynomial;
#endif
输入一元多项式的函数
此函数会把键入的多项式,按照降幂顺序排列
void Input(Polynomial& PL){
//从系数C[] 和 指数E[]中输入一元多项式的各项,建立一个按降幂方式排列的
//一元多项式PL。
double coef; int exp;
while (true)
{
Term *p = PL ->link, *pr = PL;
cin >> coef >> exp;
if(exp < 0) break;
else{
Term *newTerm = (Term *)malloc(sizeof(Term));
newTerm ->coef = coef; newTerm ->exp = exp;
while (p != NULL && exp < p ->exp)
{
pr = p;
p = p ->link;
}
if( p != NULL && p ->exp == exp){cout << "已存在exp相同的项,该项作废\n";}
else{
newTerm ->link = p;
pr ->link = newTerm;
}
}
}
}
输出保存在单链表中的一元多项式
void Output(Polynomial& PL){
//输出带头结点的一元多项式链表PL
Term *p = PL ->link;
bool flag = true;
while(p != NULL){
if(p ->coef < 0) {cout << '-'; flag = false;}
if(p ->coef > 0 && !flag ){cout << '+'; flag = false;}
if(p ->exp == 0 || fabs(p ->coef) != 1){cout << fabs(p ->coef);}
flag = false;
switch (p ->exp)
{
case 0:
break;
case 1:
cout << 'X' ;
break;
default:
cout << "X^" << p ->exp;
break;
}
p = p ->link;
}
}
运算一元多项式并输出结果
double calcValue(Polynomial& PL, double x){
Term *p = PL ->link;
if(p == NULL) return -1;
double consequence = p ->coef;
while (p != NULL)
{
if(p ->link != NULL){
consequence = consequence*pow(x,p ->exp - p ->link ->exp) + p ->link ->coef;
}
else{
consequence = consequence*pow(x,p ->exp);
}
p = p ->link;
}
return consequence;
}
main函数中的内容
int main(){
Polynomial PL;
PL = (Term *)malloc(sizeof(Term));
PL ->link = NULL;
Input(PL);
Output(PL);
cout << endl;
cout << calcValue(PL, 1);
cout << endl;
system("pause");
}