7-5 2019Final-多项式表达式解析 (20分)

 

多项式是指由若干个单项式相加组成的代数式,其中的每个单项式称为该多项式的项,每个项单项式中最高项的次数,就是这个多项式的次数。 以x为未知数的一元多项式在数学中通常以升幂排列,书写为以下形式: an​​x^n+...+a​2​​x^2+a​1​​x+a​0​​。

现在需要解析输入的一元多项式字符串,自动识别出该多项式的次数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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值