PTA 7-7 Arithmetic Problems(栈 后缀表达式)

During this winter vacation, Little Gyro went for a journey to Praha——a brand new country in the world. After arriving, Little Gyro really found a lot of differences between Praha and our country. One of the differences is based on the maths problems, which often makes Little Gyro very headache.

However, Little Gyro was invited to complete a math quiz someday, the information relating to this shown as the following:

What follows are some simple arithmetic problems. Therefore, it should be quite easy for you to get the correct answers. However, you are in a different country named Praha and the symbols for multiplication, addition, division, and subtraction follow a different logic, but fortunately all the arithmetic expressions in this country still follow the regular arithmetic rules. They are as follows:
在这里插入图片描述
It’s considered that Little Gyro can’t find the symbol ‘×’ or ‘÷’ on his laptop keyboard, so he always uses the symbol ‘*’ to represent the symbol ‘×’ as well as the symbol ‘/’ to represent the symbol ‘÷’.

Due to calculating the arithmetic problems which seems to be a little bit difficult for Little Gyro, he wrote a simple program to solve those problems perfectly at last. Now Little Gyro sends this task to you.

Input Specification:

Each input file only contains one test case.

For each case, each line contains a simple arithmetic expression S (no more than 5×10^​5
characters) from the different country Praha, which only contains non-negative integers (no more than 10​^5 ​​ ), calculating signs (only contains ‘+’, ‘-’, ‘*’, ‘/’) and spaces.

Output Specification:

For each test case, output the value of the given arithmetic expression (keep 2 decimal places). Especially, in the division operation, if the divisor is 0, output “Cannot be divided by 0”(without quotes) in the single line.

It’s guaranteed that the absolute value after each step is always between 10^​−10
​​ and 10^​10.

Sample Input 1:

1 + 1 / 1 * 1 - 1

Sample Output 1:

1.00

Sample Input 2:

2/0+0-3*4

Sample Output 2:

Cannot be divided by 0

把运算符转化对应的新的运算符

代码

#include <iostream>
#include <algorithm>
#include <string>
#include <stack>
#include <vector>
#include <map>
#include <cmath>
using namespace std;
map<string, int> m;		//运算符优先级

bool judgeNum(string str)	//判断是不是数字
{
	if(str[0] >= '0' && str[0] <= '9')
		return true;
	return false;
}

char tranform(char ch)
{
	if(ch == '-')
		return '*';
	if(ch == '/')
		return '+';
	if(ch == '+')
		return '/';
	if(ch == '*')
		return '-';
	return 0;
}

void GetMid(const string str, vector<string> &v) 			//由输入的字符串提取中缀表达式
{
	string s0;
	for (int i = 0; i < str.size(); i++)
	{
		if (str[i] == ' ')
			continue;
		s0.clear();
		if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/')
		{
			s0 += tranform(str[i]), v.push_back(s0);
			continue;
		}

		bool tag = false;
		while (str[i] >= '0' && str[i] <= '9')
			s0 += str[i], tag = true, i++;
		if (tag)
			v.push_back(s0), i--;
	}
}

void GetBack(const vector<string> v, vector<string> &vb)		//由中缀表达式Get后缀表达式(简易版, 不带括号)
{
	stack<string> s;
	for (int i = 0; i < v.size(); i++)
	{
		/*遇到数字直接加入后缀序列*/
		if (judgeNum(v[i]))
		{
			vb.push_back(v[i]);
			continue;
		}

		/*遇到运算符, 进一步判断*/
		if (s.empty() || m[v[i]] < m[s.top()])
			s.push(v[i]);
		else{
			while (!s.empty() && m[v[i]] >= m[s.top()])
				vb.push_back(s.top()), s.pop();
			s.push(v[i]);
		}
	}
	/*栈中剩余运算符的直接加入后缀表达式*/
	while (!s.empty())
		vb.push_back(s.top()), s.pop();
}

bool Calculate(const vector<string> vb, double &ans)			//计算后缀表达式
{
	stack<double> s;
	for (int i = 0; i < vb.size(); i++)
		if(judgeNum(vb[i]))		//如果是数字
			s.push(stod(vb[i]));
		else{
			double a, b;
			b = s.top(), s.pop();
			a = s.top(), s.pop();
			if(vb[i] == "+")
				a += b;
			else if(vb[i] == "-")
				a -= b;
			else if(vb[i] == "*")
				a *= b;
			else{
				if(abs(b) <= 1e-6)
					return false;
				a /= b;
			}
			s.push(a);
		}
	//cout << s.size() << endl;
	ans = s.top();
	return true;
}

int main()
{
	double ans;
	string str;
	vector<string> v, vb; //中缀表达式与后缀表达式
	getline(cin, str);
	/*初始化表示运算符的优先级*/
	m["+"] = m["-"] = 2;
	m["*"] = m["/"] = 1;

	GetMid(str, v);
	GetBack(v, vb);
	if (!Calculate(vb, ans))
		cout << "Cannot be divided by 0" << endl;
	else
		printf("%.2f\n", ans);

	system("pause");
	return 0;
}
/*
2+1-2*3-4+5
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值