多项式是指由若干个单项式相加组成的代数式,其中的每个单项式称为该多项式的项,每个项单项式中最高项的次数,就是这个多项式的次数。 以x为未知数的一元多项式在数学中通常以升幂排列,书写为以下形式: anx^n+...+a2x^2+a1x+a0。
现在需要解析输入的一元多项式字符串,自动识别出该多项式的次数highest-degree,并按照未知数x的次数,从最高的highest-degree到最低的0次, 逐一给出相应系数coefficients。
输入格式:
输入符合数学手写规则的一元多项式字符串。
例如:
2x^3+3x^2+6
输出格式:
解析该字符串输出其次数与一个系数序列。 例如: The highest degree is 3 The coefficients for degree of x from high to low are: 2 3 0 6
输入样例:
在这里给出一组输入。例如:
2x^3+3x^2+6
输出样例:
在这里给出相应的输出。例如:
The highest degree is 3
The coefficients for degree of x from high to low are: 2 3 0 6
#include <iostream>
#include <string>
using namespace std;
const int max = 100;
int main()
{
char dxs[100];
int conf[max][2] = { 0 };
cin.getline(dxs, 100);
char* p, * r;
string sa, sb;
int a, b, id = 0;
size_t cnta,sp;
p = strtok_s(dxs, "+", &r);//以+号为分隔符,拆分多项式
while (p)
{//对拆分出的项进行分析,取得系数和次数
string str(p);
sp=str.find_first_not_of(" ");
if (sp != string::npos) str.erase(0, sp);//去掉前面的空格,否则字符串转数字会出错
sp = str.find_last_not_of(" ");
if (sp != string::npos) str.erase(sp + 1, str.size() - sp);//去掉后面的空格
cnta = str.find("x^");
if (cnta == 0)
{
a = 1;
sb = str.substr(2, str.length() - 2);
b = stoi(sb, 0, 10);
}
else if (cnta == string::npos) {//处理1次项和常数项
if (p[str.length() - 1] == 'x')
{
sb = str.substr(0, str.length() - 1);
if (sb == "")
{
a = 1;
b = 1;
}
else {
a = stoi(sb, 0, 10);
b = 1;
}
}
else {
a = stoi(str, 0, 10);
b = 0;
}
}
else {
sa = str.substr(0, cnta);
a = stoi(sa, 0, 10);
sb = str.substr(cnta + 2, str.length() - cnta - 2);
b = stoi(sb, 0, 10);
}
conf[id][0] = a;
conf[id][1] = b;
id++;
p = strtok_s(NULL, "+", &r);
}
int temp1, temp2;
for (int i = 0; i < id - 1; i++)//排序
{
for (int j = 0; j < id - 1 - i; j++)
{
if (conf[j][1] < conf[1 + j][1])
{
temp1 = conf[j][0];
temp2 = conf[j][1];
conf[j][0] = conf[j + 1][0];
conf[j][1] = conf[j + 1][1];
conf[j + 1][0] = temp1;
conf[j + 1][1] = temp2;
}
}
}
int rs[max][2] = { 0 };
int sn = 0;
for (int i = 0; i < id; i++)//不连续的项插入0值
{
rs[sn][0] = conf[i][0];
rs[sn][1] = conf[i][1];
if (conf[i][1] - conf[i + 1][1] > 1)
{
sn += conf[i][1] - conf[i + 1][1];
}
else {
sn++;
}
}
cout << "The highest degree is " << rs[0][1] << endl;
cout << "The coefficients for degree of x from high to low are:";
if (sn == rs[0][1])//没有常数项时,输出常数项为0
{
sn++;
}
for (int i = 0; i < sn; i++)
{
cout << ' ' << rs[i][0];
}
return 0;
}