C++实现表达式求值(括号,小数点,负数)

难得闲来无事,写一篇博客岂不是美滋滋。

表达式求值的思路主要是将中缀表达式转换为后缀表达式,然后由后缀表达式进行求值,这里用到的数据结构主要是栈。

中缀转后缀:遍历表达式,如果是数字,就直接输出,如果是操作符,就需要判断此时栈内是否为空或者栈顶是否为左括号,如果是的话,就直接进栈,否则就需要与栈顶元素进行比较,如果优先级大于栈顶元素,直接进栈,如果小于或等于,则需要先出栈,再进栈。当遍历完整个表达式之后,如果栈不为空,则依次出栈输出。

后缀求值:遍历后缀表达式,如果是数字,直接进栈,如果是操作符,则将栈顶两个元素出栈,进行运算,运算结果进行入栈,最终栈顶元素就是表达式的值。

上代码

(1)字符串预处理

这里主要是处理类似 -2+3,1+(-3+2)这类负数问题

string format(string str){
	for(int i = 0;i < str.length(); i++){
		if(str[i] == '-'){
			if(i == 0){
				str.insert(0,1,'0');
			}else if(str[i-1] == '('){
				str.insert(i,1,'0');
			}
		}
		
	}
	return str;
}

(2)确定操作符优先级

int prior(char c){
	if(c == '+' || c == '-'){
		return 1;
	}else if(c == '*' || c == '/'){
		return 2;
	}else{
		return 0;
	}
	
} 

(3)中缀表达式转后缀表达式

vector<string> hz(string str){
	vector<string> vs;
	stack<char> st;
	for(int i = 0;i < str.length(); i++){
		string tmp = "";
		switch(str[i]){
			case '+':
			case '-':
			case '*':
			case '/':
				if(st.empty() || st.top() == '('){
					st.push(str[i]);
				}else{
					while(!st.empty() && prior(st.top()) >= prior(str[i]) ){
						tmp += st.top();
						vs.push_back(tmp);
						st.pop();
						tmp = "";
					}
					st.push(str[i]);
				}
				break;
			case '(':
				st.push(str[i]);
				break;
			case ')':
				while(st.top() != '('){
					tmp += st.top();
					vs.push_back(tmp);
					st.pop();
					tmp = "";
				}
				st.pop();
				break;
			default:
			if((str[i]>='0' && str[i]<='9')){
            	tmp += str[i];
            	while(i+1<str.size() && str[i+1]>='0' && str[i+1]<='9'||str[i+1] == '.')
            	{
                	tmp += str[i+1];//若是连续数字
                	++i;
   				}
            	vs.push_back(tmp);
  			}
		}
	}
	while(!st.empty()){
		string tmp = "";
		tmp += st.top();
		vs.push_back(tmp);
		st.pop();
	}
	return vs;
}

(4)计算后缀表达式

double result(vector<string> bh){
	stack<double> st;
	double num,op1,op2;
	for(int i = 0;i < bh.size(); i++){
		string tmp = bh[i];
		if(tmp[0] >= '0'&&tmp[0] <= '9'){
			num = atof(tmp.c_str());
			st.push(num);
		}
		else if(bh[i]=="+")
        {
            op2=st.top();
            st.pop();
            op1=st.top();
            st.pop();
            st.push(op1+op2);
        }
        else if(bh[i]=="-")
        {
            op2=st.top();
            st.pop();
            op1=st.top();
            st.pop();
            st.push(op1-op2);
        }
        else if(bh[i]=="*")
        {
            op2=st.top();
            st.pop();
            op1=st.top();
            st.pop();
            st.push(op1*op2);
        }
        else if(bh[i]=="/")
        {
            op2=st.top();
            st.pop();
            op1=st.top();
            st.pop();
            st.push(op1/op2);
        }
	}
	return st.top();
}

完整代码:

#include<iostream>
#include<algorithm>
#include<stack>
#include<stdlib.h>
#include<vector>
#include<string>
using namespace std;
string format(string str){
	for(int i = 0;i < str.length(); i++){
		if(str[i] == '-'){
			if(i == 0){
				str.insert(0,1,'0');
			}else if(str[i-1] == '('){
				str.insert(i,1,'0');
			}
		}
		
	}
	return str;
}
int prior(char c){
	if(c == '+' || c == '-'){
		return 1;
	}else if(c == '*' || c == '/'){
		return 2;
	}else{
		return 0;
	}
	
} 
vector<string> hz(string str){
	vector<string> vs;
	stack<char> st;
	for(int i = 0;i < str.length(); i++){
		string tmp = "";
		switch(str[i]){
			case '+':
			case '-':
			case '*':
			case '/':
				if(st.empty() || st.top() == '('){
					st.push(str[i]);
				}else{
					while(!st.empty() && prior(st.top()) >= prior(str[i]) ){
						tmp += st.top();
						vs.push_back(tmp);
						st.pop();
						tmp = "";
					}
					st.push(str[i]);
				}
				break;
			case '(':
				st.push(str[i]);
				break;
			case ')':
				while(st.top() != '('){
					tmp += st.top();
					vs.push_back(tmp);
					st.pop();
					tmp = "";
				}
				st.pop();
				break;
			default:
			if((str[i]>='0' && str[i]<='9')){
            	tmp += str[i];
            	while(i+1<str.size() && str[i+1]>='0' && str[i+1]<='9'||str[i+1] == '.')
            	{
                	tmp += str[i+1];//若是连续数字
                	++i;
   				}
            	vs.push_back(tmp);
  			}
		}
	}
	while(!st.empty()){
		string tmp = "";
		tmp += st.top();
		vs.push_back(tmp);
		st.pop();
	}
	return vs;
}
double result(vector<string> bh){
	stack<double> st;
	double num,op1,op2;
	for(int i = 0;i < bh.size(); i++){
		string tmp = bh[i];
		if(tmp[0] >= '0'&&tmp[0] <= '9'){
			num = atof(tmp.c_str());
			st.push(num);
		}
		else if(bh[i]=="+")
        {
            op2=st.top();
            st.pop();
            op1=st.top();
            st.pop();
            st.push(op1+op2);
        }
        else if(bh[i]=="-")
        {
            op2=st.top();
            st.pop();
            op1=st.top();
            st.pop();
            st.push(op1-op2);
        }
        else if(bh[i]=="*")
        {
            op2=st.top();
            st.pop();
            op1=st.top();
            st.pop();
            st.push(op1*op2);
        }
        else if(bh[i]=="/")
        {
            op2=st.top();
            st.pop();
            op1=st.top();
            st.pop();
            st.push(op1/op2);
        }
	}
	return st.top();
}
void solve(string str){
	str = format(str);
	vector<string> bh = hz(str);
	double k = result(bh);
	if((int)k == k){
		cout<<k<<endl;
	} else{
		printf("%.1f",k);
		cout<<endl;
	}
	
}
int main(){
	string str;
	while(getline(cin,str)){
		solve(str);
	}
}


  • 13
    点赞
  • 88
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值