题目描述
输入一个字符串形式的表达式,该表达式中包括整数,四则运算符(+、-、*、/),括号,三角函数(sin(x)、cos(x)、tan(x)),底数函数(lg(x)、ln(x)),计算该表达式的值
输入
输入一个字符串形式的表达式,保证中间及最终结果不超出double的范围
输出
表达式的值,保留6位小数
样例输入
3
3+5
((2-1)*5-1)*6
1+cos(0)
样例输出
3.000000
8.000000
24.000000
2.000000
来源
#include<iostream> #include<cstdio> #include<cmath> #include<string> #include<stack> using namespace std; int main() { string str; while(cin>>str) { stack<double>num; stack<char>chr; for(int i=0;i<str.size();i++) { //cout<<str[i]<<" "; double number=0; if(str[i]>=48&&str[i]<=57) { number=str[i]-48; while(str[i+1]>=48&&str[i+1]<=57) { number=number*10+(str[i+1]-48); i++; } num.push(number); } else if(str[i]==‘(‘) chr.push(str[i]); else if(str[i]==‘+‘||str[i]==‘-‘) chr.push(str[i]); else if(str[i]==‘*‘||str[i]==‘/‘) { char t=str[i]; i++; number=str[i]-48; while(str[i+1]>=48&&str[i+1]<=57) { number=number*10+(str[i+1]-48); i++; } num.push(number); double x=num.top();num.pop(); double y=num.top();num.pop(); double n=0; if(t==‘*‘) n=x*y; else n=x/y; num.push(n); } else if(str[i]==‘)‘) { char temp=chr.top();chr.pop(); double x=num.top();num.pop(); double y=num.top();num.pop(); double n=0; if(temp==‘+‘) n=x+y; else if(temp==‘-‘) n=y-x; num.push(n); chr.pop(); chr.pop(); } else if(str[i]==‘s‘||str[i]==‘c‘||str[i]==‘t‘) { char t=str[i]; i=i+4; number=str[i]-48; while(str[i+1]>=48&&str[i+1]<=57) { number=number*10+(str[i+1]-48); i++; } if(t==‘s‘) { number=sin(number); num.push(number); } else if(t==‘t‘) { number=tan(number); num.push(number); } else if(t==‘c‘) { number=cos(number); num.push(number); } i++; } else if(str[i]==‘l‘) { char t=str[i+1]; i=i+3; number=str[i]-48; while(str[i+1]>=48&&str[i+1]<=57) { number=number*10+(str[i+1]-48); i++; } if(t==‘g‘) { number=log10(number); num.push(number); } else if(t==‘n‘) { number=log(number); num.push(number); } i++; } } while(chr.size()>0&&chr.size()<100&&num.size()!=1) { char temp=chr.top();chr.pop(); double x=num.top();num.pop(); double y=num.top();num.pop(); double n=0; if(temp==‘+‘) n=x+y; else if(temp==‘-‘) n=y-x; else if(temp==‘(‘) continue; num.push(n); } printf("%lf",num.top());cout<<endl; } return 0; }