XYNUOJ 第四次考試 表示式求值
阿新 • • 發佈:2019-01-02
問題 B: 表示式求值
時間限制: 3 Sec 記憶體限制: 6 MB[提交][狀態][討論版]
題目描述
實現輸入一個表示式求出它的值的計算器,比如輸入:“1+2/4=”,程式就輸出1.50(結果保留兩位小數)
輸入
第一行輸入一個整數n,共有n組測試資料(n<10)。 每組測試資料只有一行,是一個長度不超過1000的字串,表示這個運算式,每個運算式都是以“=”結束。這個表示式裡只包含+-*/與小括號這幾種符號。其中小括號可以巢狀使用。資料保證輸入的運算元中不會出現負數。 資料保證除數不會為0輸出
每組都輸出該組運算式的運算結果,輸出結果保留兩位小數。樣例輸入
2 1.000+2/4= ((1+2)*5+1)/4=
樣例輸出
1.50
4.00
#include<stdio.h> #include<string.h> #include<stack> #include<ctype.h> #include<stdlib.h> using namespace std; int priority(char c) { if(c=='=') return 0; if(c=='+') return 1; if(c=='-') return 1; if(c=='*') return 2; if(c=='/') return 2; return 0; } void compute(stack<double>& num,stack<char>& ch) { double b=num.top(); num.pop(); double a=num.top(); num.pop(); switch(ch.top()) { case'+': num.push(a+b); break; case'-': num.push(a-b); break; case'*': num.push(a*b); break; case'/': num.push(a/b); break; } ch.pop(); } int main() { int n; char str[1005]; stack<double> num; stack<char> ch; scanf("%d",&n); while(n--) { scanf("%s",&str); int len=strlen(str); for(int i=0;i<len;i++) { if(isdigit(str[i])) { double n=atof(&str[i]); while(i<len&&(isdigit(str[i])||str[i]=='.')) i++; i--; num.push(n); } else { if(str[i]=='(') ch.push(str[i]); else if(str[i]==')') { while(ch.top()!='(') compute(num,ch); ch.pop(); } else if(ch.empty()||priority(str[i])>priority(ch.top())) ch.push(str[i]); else { while(!ch.empty() && priority(str[i])<=priority(ch.top())) compute(num,ch); ch.push(str[i]); } } } ch.pop(); printf("%.2f\n",num.top()); } return 0; }