题目描述:一元n次多项式的处理
问题描述:符号处理是一类非数值性问题,一元多项式就是符号处理的一类实例。一个一元n次多项式的一般形式如下:
Pn(x)=p1xe1+p2xe2+…各+pmxem
其中p1,p2,…, pm为项的系数,非零;
e1,e2,…, em 为各项的指数,满足0£e1£e2 £... £em
现要求在计算机中存储这样的多项式,并能对它们进行处理,如:加法、减法、乘法等等。
// duoxiangshi1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
using namespace std;
void Show(double a1[100], double a2[100]);
void Jiafa(double a1[100], double a2[100]);
void Jianfa(double a1[100], double a2[100]);
void Chengfa(double a1[100], double a2[100]);
int main()
{
for (int i = 0;; i++)
{
//int zhishu1[100] = { 0 };
double xishu1[100] = { 0 };
//int zhishu2[100] = { 0 };
double xishu2[100] = { 0 };
//double xishu3[100] = { 0 };
cout << "请输入第一个多项式" << endl;
int flag = 0;
do
{
cout << "请分别输入系数和指数:如果输入的是最后一项,在后边输入1,否则后边输入0" << endl;
int a1, f;
double b1;
cin >> b1 >> a1 >> f;
flag = f;
xishu1[a1] = b1;
} while (flag == 0);
cout << "请输入第二个多项式" << endl;
flag = 0;
do
{
cout << "请分别输入系数和指数:如果输入的是最后一项,在后边输入1,否则后边输入0" << endl;
int a2, f1;
double b2;
cin >> b2 >> a2 >> f1;
flag = f1;
xishu2[a2] = b2;
} while (flag == 0);
Show(xishu1, xishu2);
Jiafa(xishu1, xishu2);
Jianfa(xishu1, xishu2);
Chengfa(xishu1, xishu2);
cout << "是否继续?继续--->输入Y,退出输入--->N" << endl;
char panduan;
cin >> panduan;
if (panduan == 'N')
break;
}
return 0;
}
void Show(double a1[100], double a2[100])
{
cout << "这是你输入的两个多项式" << endl;
int i;
for (i = 1; i < 100; i++)
{
if (a1[i] != 0)
{
cout << a1[i] << "X^" << i << '+';
}
}
/*if (i == 0 && a1[i] != 0)
{
cout << a1[0];
}*/
cout << a1[0];
cout << endl;
for (i = 1; i < 100; i++)
{
if (a2[i] != 0)
{
cout << a2[i] << "X^" << i << '+';
}
}
/*if (i == 0 && a2[i] != 0)
{
cout << a2[0];
}*/
cout << a2[0];
cout << endl;
}
void Jiafa(double a1[100], double a2[100])
{
cout << "两个多项式的和是:" << endl;
int i;
for (i = 1; i < 100; i++)
{
if (a1[i] != 0 || a2[i] != 0)
{
cout << a2[i] + a1[i] << "X^" << i << '+';
}
}
cout << a2[0]+a1[0];
cout << endl;
}
void Jianfa(double a1[100], double a2[100])
{
cout << "两个多项式的差是:" << endl;
int i;
for (i = 1; i < 100; i++)
{
if ((a1[i] != 0 || a2[i] != 0) && a1[i] - a2[i] != 0)
{
if(a1[i] - a2[i] > 0)
cout << a1[i] - a2[i] << "X^" << i << '+';
else
{
cout <<'('<< a1[i] - a2[i]<<')' << "X^" << i << '+';
}
}
}
cout << a2[0] + a1[0];
cout << endl;
}
void Chengfa(double a1[100], double a2[100])
{
double xishu3[100] = { 0 };
cout << "两个多项式的乘是:" << endl;
int i, j;
for (i = 0; i < 100; i++)
{
for (j = 0; j < 100; j++)
{
xishu3[i + j] = xishu3[i + j] + a1[i] * a2[j];
}
}
for (i = 1; i < 100; i++)
{
if (xishu3[i] != 0)
{
cout << xishu3[i] << "X^" << i << '+';
}
}
/*if (i == 0 && a1[i] != 0)
{
cout << a1[0];
}*/
cout << xishu3[0];
cout << endl;
}