杭电OJ - 1237 简单计算器(栈应用)

HDOJ-1327 简单计算器

problem
读入一个只包含+, - ,*,/的非负整数计算表达式,计算该表达式的值

Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。

Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。

Sample input
1 + 2
4 + 2 * 5 - 7/11
0
Sample output
3.00
13.36

#include <cstring>
#include <cstdio>
#include <stack>
#include <cmath>
#include <cstdlib>
using namespace std;

stack <double> N; //操作数栈 
stack <char> O; //操作符栈 
double calcul(char oper)
{
    
    
	double a = N.top(), b;
	N.pop();
	b = N.top();
	N.pop();
	switch(oper)
	{
    
    
		case '+': return b + a;
		case '-': return b - a;
		case '*': return b * a;
		case '/': return b / a;
	}
}
int main()
{
    
    
	int i , len;
	char s[201], oper;
	double num;
	while(gets(s))
	{
    
    
		len = strlen(s);
		if(len == 1 && s[0] == '0') break;
		i = 0;
		while(i < len)
		{
    
    
			num = 0;
			if(s[i] == ' ') i++;
			while(s[i] >= '0' && s[i] <= '9' && i < len)
			{
    
    
				num = num*10 + s[i] - '0';
				i++;
			}
			while(s[i] == ' ') i++;
			N.push(num); 
			switch(s[i])//处理操作符 
			{
    
    
				case '+':case'-':
					if(!O.empty()){
    
    
						oper = O.top();
						O.pop();
						N.push(calcul(oper));
					}
					O.push(s[i]);break;
				case '*':case '/':
					if(!O.empty()&&(O.top() == '*' || O.top() == '/')){
    
     
						oper = O.top();
						O.pop();
						N.push(calcul(oper));
					}
					O.push(s[i]);break;
				default:break;
			}
			i++;
		}
		while(!O.empty()){
    
    
			oper = O.top();
			O.pop();
			N.push(calcul(oper));
		}
		printf("%.2lf\n", N.top());
		N.pop();
	}
	return 0; 
}

参考:关于中缀表达式的理解https://blog.csdn.net/zhengxu001/article/details/8022085

猜你喜欢

转载自blog.csdn.net/qq_29757633/article/details/87122797