北理工10计算机复试上机

中缀表达式转后缀表达式并计算相应的值

注意:值可能为小数

#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <queue>
using namespace std; 

double cal(queue<string> su){
    
    
	stack<double> nums;
	while(!su.empty()){
    
    
		if('0' <= su.front()[0] && su.front()[0] <= '9'){
    
    //数字字符串转换 
		 	char ch[20];
			strcpy(ch, su.front().data());//char数组可直接给string类型赋值,反之不行,可以使用strcpy()函数结合string类型的data()方法 
		 	//char ch[20] = "2.34";
			nums.push(atof(ch));//atof()字符串转换浮点型数字 ,相应的还有atoi(),atol(),在<cstdlib>中 
			cout<<"进栈:"<<atof(ch)<<endl;
			su.pop();
		}else{
    
    //注意两个操作数的赋值是倒过来的 
			double b = nums.top();
			nums.pop();
			double a = nums.top();
			nums.pop();
			char c = su.front()[0]; 
			if(c == '+'){
    
    
				nums.push(a + b);
				cout<<"进栈:"<<a + b<<endl;
			}else if(c == '-'){
    
    
				nums.push(a - b);
				cout<<"进栈:"<<a - b<<endl;
			}else if(c == '*'){
    
    
				nums.push(a * b);
				cout<<"进栈:"<<a * b<<endl;
			}else{
    
    
				nums.push(a / b);
				cout<<"进栈:"<<a / b<<endl;
			}
			su.pop();
		}
	}
	
	return nums.top();
}
int main(int argc, char *argv[]) {
    
    
	map<char, int> m;
	m['+'] = 0;
	m['-'] = 0;
	m['*'] = 1;
	m['/'] = 1;
	string str;
	stack<char> s;
	queue<string> suffix; 
	int i;
	string temp;
	while(cin>>str){
    
    
		for(i = 0; i < str.size(); ++i){
    
    
			if('0' <= str[i] && str[i] <= '9'){
    
    
				temp = "";
				while(('0' <= str[i] && str[i] <= '9') || str[i] == '.'){
    
    //截取数字 
					
					temp += str[i]; 
					++i;
				}
				--i;//注意		
				cout<<temp<<" ";
				suffix.push(temp);		
			}else if(s.size() == 0 || str[i] == '('){
    
    
				s.push(str[i]);
			}else if(str[i] == ')'){
    
    
				temp = "a";//将单个字符转换成字符串:
				//法一:定义一个长度为1的字符串,然后直接替换第一个位置  
				//法二:将字符赋值给字符数组,char ch[2] = {c,0},第二个0为字符串结束符\0,再将字符数组赋值给字符串 
				//注意不能使用:"" + c; 
				while(!s.empty() && s.top() != '('){
    
    //注意 
					temp[0] = s.top();
					cout<<temp<<" ";
					suffix.push(temp);
					s.pop();
				}
				s.pop();//左括号舍弃 
			}else{
    
    
				if(m[str[i]] > m[s.top()] || s.top() == '('){
    
    
					s.push(str[i]);
				}else{
    
    
					temp = "a";
					while(!s.empty() && m[str[i]] <= m[s.top()]){
    
    
						temp[0] = s.top();
						cout<<temp<<" ";
						suffix.push(temp);
						s.pop();
					}
					s.push(str[i]);//注意,第一遍忘了放 
				}
			}
		}
		temp = "a";
		while(!s.empty()){
    
    
			temp[0] = s.top();
			cout<<temp<<" ";
			suffix.push(temp);
			s.pop();
		}
		cout<<endl;
		double re = cal(suffix);
		cout<<"结果是:";
		cout<<re<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/baidu_36004106/article/details/104905789