Hangdian OJ - 1237 simple calculator (stack application)

HDOJ-1327 Simple Calculator

problem
Read in a non-negative integer calculation expression containing only +, -, *, /, and calculate the value of the expression

Input
test input contains several test cases, each test case occupies one line, each line does not exceed 200 characters, and integers and operators are separated by a space. There are no illegal expressions. When there is only 0 in a line, the input ends, and the corresponding result is not output.

Output
outputs 1 line for each test case, that is, the value of the expression, accurate to 2 decimal places.

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; 
}

Reference: Understanding of infix expressions https://blog.csdn.net/zhengxu001/article/details/8022085

Guess you like

Origin blog.csdn.net/qq_29757633/article/details/87122797