以前不想用栈写表达式求值,代码都不想看,现在专门学了编译原理来写一下。
原理百度就有了。
好久没用openjudge了,这个oj的编译器是真的傻逼。
/*#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<sstream>
#include<queue>
#include<list>
#include<bitset>
#include<stack>
#include<bitset>
#include<iomanip>
#include<set>
#include<cmath>
#include<map>
#include<functional>
#define int long long
#define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define _BYTE unsigned char
#define HIBYTE(x) (*((_BYTE*)&(x)+1))
#define eps 1e-8
using namespace std;*/
//#define double long double
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char s[100005];
int indexstring,len;
double factor();
double term();
double expression();
double factor()
{
if(s[indexstring]=='(')
{
indexstring++;
return expression();
}
char *last;
double number=strtod(indexstring+s,&last);
indexstring=last-s;
return number;
}
double term()
{
double number1=factor();
while(s[indexstring]=='*'||s[indexstring]=='/')
{
char c=s[indexstring++];
double number2=factor();
if(c=='*')
{
number1=number1*number2;
}
else
{
number1=number1/number2;
}
}
return number1;
}
double expression()
{
double number1=term();
while(s[indexstring]=='+'||s[indexstring]=='-')
{
char c=s[indexstring++];
double number2=term();
if(c=='+')
{
number1=number1+number2;
}
else
{
number1=number1-number2;
}
}
if(s[indexstring]==')')indexstring++;
return number1;
}
signed main()
{
//IO;
scanf("%s",s+1);
len=strlen(s+1);
indexstring=1;
printf("%.2f",expression());
}