HDU--1237--表达式求值--栈的运用--掌握模板

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

Input

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

Output

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

思路:代码参考:https://blog.csdn.net/sinat_26019265/article/details/79284966

#include<iostream>
#include<stack>
#include<cstring>
using namespace std;  
stack<char>str;
stack<double>num;
void Calculation(){
	double a,b;
	a=num.top() ;
	num.pop();
	b=num.top() ;
	num.pop(); 
	switch(str.top()){
		case '+': num.push(a+b);break; 
		case '-': num.push(b-a);break;
		case '*': num.push(a*b);break;
		case '/': num.push(b/a);break;		
	}
	str.pop();
}
int est_check(char a){
	char b=str.top();
	int l,r;
	switch(a){
		case '#': l=0;break;
		case '(': l=0;break;	
		case ')': l=0;break;	
		case '+': l=1;break;
		case '-': l=1;break;
		case '*': l=2;break;
		case '/': l=2;break;				
	}
	switch(b){
		case '#': r=0;break;
		case '(': r=0;break;	
		case ')': r=0;break;	
		case '+': r=1;break;
		case '-': r=1;break;
		case '*': r=2;break;
		case '/': r=2;break;				
	}
	if(l>r){
	   str.push(a);
	   return 1;	
	}else if(l==r&&a=='#'){
		return 1;
	}else{
	   Calculation();	
	   return 0;
	}
}
int main(){//输入方式采用scanf()函数,数字+操作符 	
	int n,leng;
	int number;
	char ch;
	str.push('#');//操作符入栈 
	int f=0;
	while(~scanf("%d%c",&number,&ch)){//ch用于接收空格	
   	    if(f==0&&number==0&&ch=='\n')	break;//结束输入 
	    else if(((number==0&&f==1)||number!=0)&&ch=='\n'){
	    	num.push(number);//这里好难理解 
	    	while(est_check('#')==0);           
	    	printf("%.2lf\n",num.top());//精确到小数点后2位
	    	num.pop(); 
	    	f=0;
		}else{
			f=1;
			scanf("%c ",&ch);//输入操作符 
			num.push(number);//数字入栈 
			while(est_check(ch)==0);//这里好难理解         
		}
	}
}
/*Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output
3.00
13.36*/ 
原创文章 246 获赞 109 访问量 1万+

猜你喜欢

转载自blog.csdn.net/queque_heiya/article/details/105771238
今日推荐