nyoj35 表达式求值

http://nyoj.top/problem/35 

#include <bits/stdc++.h>
using namespace std;

int cmp[7][7]={// +,-,*,/,(,),#,的优先级 1表示栈顶操作符比当前字符串操作符大,-1表示小,=则为左右括号或两个##,100代表不存在 
	1,1,-1,-1,-1,1,1,
	1,1,-1,-1,-1,1,1,
	1,1,1,1,-1,1,1,
	1,1,1,1,-1,1,1,
	-1,-1,-1,-1,-1,0,100,
	1,1,1,1,100,1,1,
	-1,-1,-1,-1,-1,100,0,
};
int isnum(char c){ 
	if(c>='0'&&c<='9'||c=='.')//'.'是否为小数 
	return 1;
	return 0;
}
int ctoi(char c){// char to int 
	switch(c){
		case '+':
			return 0;
		case '-':
			return 1;
		case '*':
			return 2;
		case '/':
			return 3;
		case '(':
			return 4;
		case ')':
			return 5;
		case '#':
			return 6;
	}
}
double cal(double x,char c,double y){ 
	switch(c){
		case '+':
			return x+y;
		case '-':
			return x-y;
		case '*':
			return x*y;
		case '/':
			return x/y;
	}
}
int main(){
	int n;
	cin>>n;
	char str[1005];
	getchar();
	while(n--){
		stack<char>optr;
		stack<double>opnd;
		cin>>str;
		int len=strlen(str);
		str[len-1]='#';//表达式末尾改为'#'与栈中的'#'对应 
		optr.push('#');
		for(int i=0;i<len;i++){
			if(isnum(str[i])){
				opnd.push(atof(&str[i]));//ascii to float
				while(isnum(str[i+1]))
				i++;
			}
			else{
				if(cmp[ctoi(optr.top())][ctoi(str[i])]==1){
					double a=opnd.top(); opnd.pop();
					double b=opnd.top(); opnd.pop();
					char c=optr.top(); optr.pop();
					opnd.push(cal(b,c,a));
					i--;
				}
				else if(cmp[ctoi(optr.top())][ctoi(str[i])]==-1){
					optr.push(str[i]);
				}
				else {
					optr.pop();
				}
			}
		}
		printf("%.2lf\n",opnd.top());
	}
}

猜你喜欢

转载自blog.csdn.net/skykone1/article/details/85239019