NYOJ 305 表达式求值 (简单栈应用)

题意:

求一个表达式的值,这个表达式只有add(a,b),min(a,b),max(a,b)这些函数。

题解:

直接乱搞。注意可能有浮点数。

#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<string>
#define B(x) (1<<(x))
using namespace std;
typedef long long ll;
void cmax(int &a,int b){ if(b>a)a=b; }
void cmin(int &a,int b){ if(b<a)a=b; }
void cmax(ll &a,ll b){ if(b>a)a=b; }
void cmin(ll &a,ll b){ if(b<a)a=b; }
void add(int &a,int b,int mod){ a=(a+b)%mod; }
void add(ll &a,ll b,ll mod){ a=(a+b)%mod; }
void add(int &a,int b){ a+=b; }
void add(ll &a,ll b){ a+=b; }
const int oo=0x3f3f3f3f;
const ll MOD=1000000007;
char str[305],s[305];
stack<string>op;
stack<double>num;

double calc(double a,double b,string s){
	if(s=="add") return a+b;
	if(s=="max") return max(a,b);
	if(s=="min") return min(a,b);
}

int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		while(!num.empty())num.pop();
		while(!op.empty())op.pop();
		scanf("%s",str);
		for(int i=0;str[i];i++){
			if(isalpha(str[i])){
				int k=0;
				s[k++]=str[i++];
				s[k++]=str[i++];
				s[k++]=str[i++];
				s[k]='\0';
				op.push(s);
			}else if(isdigit(str[i])){
				int k=0;
				for(;str[i]!=','&&str[i]!=')'&&str[i];i++)
					s[k++]=str[i];
				s[k]='\0';
				num.push(atof(s));
				if(str[i]==')')i--;
			}else if(str[i]==')'){
				double a=num.top();num.pop();
				double b=num.top();num.pop(); 
				num.push(calc(a,b,op.top()));
				op.pop();
			}
		}
		while(!op.empty()){
			double a=num.top();num.pop();
			double b=num.top();num.pop(); 
			num.push(calc(a,b,op.top()));
			op.pop();
		}
		cout<<num.top()<<endl;
	}
    return 0;
}
/*
3
add(1.478,2.1245) 
max(1.789,999.45) 
add(min(1.45,1000.787),add(100.123,99.77)) 
*/




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值