zoukankan      html  css  js  c++  java
  • infix expression 计算完全版

    #include<iostream>
    #include<stack>
    #include<string>
    using namespace std;
    
    char compare(char tp, char op)
    {
    	if (((tp == '+' || tp == '-') && (op == '*' || op == '/')) || (tp == '#'))
    		return '<';
    	else if (tp == '('&&op != ')')
    		return '<';
    	else if ((tp == '*' || tp == '/'||tp=='+'||tp=='-') && (op == '('))
    		return '<';
    	return '>';
    }
    
    int compute(int n1, int n2, char op)
    {
    	if (op == '+')
    		return n1 + n2;
    	else if (op == '-')
    		return n1 - n2;
    	else if (op == '*')
    		return n1*n2;
    	else if (op == '/')
    		return n2 / n1;
    }
    
    int main()
    {
    	stack<char>num;
    	stack<char>oper;
    
    	oper.push('#');
    
    	string s;
    	cin >> s;
    
    	for (int i = 0; i<s.length(); i++)
    	{
    		if (s[i] == '0' || s[i] == '1' || s[i] == '2' || s[i] == '3' || s[i] == '4' || s[i] == '5' || s[i] == '6' || s[i] == '7' || s[i] == '8' || s[i] == '9')
    			num.push(s[i]);
    		else
    		{
    			char comp = compare(oper.top(), s[i]);
    			if (comp == '<')
    				oper.push(s[i]);
    			else if (comp == '>')
    			{
    				if (s[i] == ')')
    				{
    					if (num.size() != 1)
    					{
    						while (oper.top() != '(')
    						{
    							int num1 = num.top() - '0';
    							num.pop();
    							int num2 = num.top() - '0';
    							num.pop();
    							int result = compute(num1, num2, oper.top());
    							num.push(result + '0');
    							oper.pop();
    						}
    					}
    					oper.pop();
    				}
    				else
    				{
    					int num1 = num.top();
    					num.pop();
    					int num2 = num.top();
    					num.pop();
    					char result = compute(num1, num2, oper.top());
    					num.push(result);
    					oper.pop();
    					oper.push(s[i]);
    				}
    			}
    		}
    	}
    
    	if (num.size() != 1)
    	{
    		while (oper.top() != '#')
    		{
    			int num1 = num.top()-'0';
    			num.pop();
    			int num2 = num.top()-'0';
    			num.pop();
    			int result = compute(num1, num2, oper.top());
    			num.push(result+'0');
    			oper.pop();
    		}
    	}
    
    	cout << num.top() << endl;
    
    	return 0;
    }
    

      

  • 相关阅读:
    PHP返回随机颜色
    SQL Server 系统表介绍:sys.dm_exec_requests
    ORA27300 ORA27301 ORA27302 ORA27157
    Linux的subversion安装配置
    批处理计算n天前\后的日期
    Linux下vsftp配置
    RedHat Linux 5企业版开启VNCSERVER远程桌面功能
    WAS 6.1命令行(静默)安装
    五板斧封杀Windows操作系统默认共享(图)
    Select Top在不同数据库中的使用用法:
  • 原文地址:https://www.cnblogs.com/KennyRom/p/5979876.html
Copyright © 2011-2022 走看看