1918 Problem A 简单计算器
生活随笔
收集整理的這篇文章主要介紹了
1918 Problem A 简单计算器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題 A: 簡單計算器
時間限制: 1 Sec 內存限制: 32 MB
提交: 367 解決: 175
題目描述
讀入一個只包含 +, -, *, / 的非負整數計算表達式,計算該表達式的值。
輸入
測試輸入包含若干測試用例,每個測試用例占一行,每行不超過200個字符,整數和運算符之間用一個空格分隔。沒有非法表達式。當一行中只有0時輸入結束,相應的結果不要輸出。
輸出
對每個測試用例輸出1行,即該表達式的值,精確到小數點后2位。
樣例輸入
30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0
樣例輸出
12178.21
經驗總結
原理為中綴表達式轉后綴表達式,最后按照相應規則處理數字棧和符號棧即可,似乎沒有坑~~
正確代碼
#include <cstdio> #include <iostream> #include <string> #include <unordered_map> #include <stack> #include <sstream> using namespace std; int str_to_int(const string &string_temp) {int temp;stringstream stream(string_temp);stream>>temp;return temp; } void compute(stack<double> &number,stack<string> &sign) {double b=number.top();number.pop();double a=number.top();number.pop();string op=sign.top();sign.pop();if(op=="+"){number.push(a+b);}else if(op=="-"){number.push(a-b);}else if(op=="*"){number.push(a*b);}else{number.push(a/b);} } double dispose(unordered_map<string,int> isp,unordered_map<string,int> osp,string str) {stack<double> number;stack<string> sign;int flag=0;while(str.empty()==false){string temp;int pos=str.find(" ");if(pos!=string::npos){temp+=str.substr(0,pos);str.erase(0,pos+1);}else{temp=str;str.clear();}if(flag==0){number.push(str_to_int(temp));flag=1; }else{if(sign.empty()==false){if(isp[sign.top()]>=osp[temp]){while(sign.empty()==false){if(isp[sign.top()]<osp[temp])break;compute(number,sign);}}}sign.push(temp);flag=0;}}while(sign.empty()==false){compute(number,sign);}return number.top(); }int main() {char a[210];string temp;while(gets(a)){for(int i=0;i<200;i++){if(a[i]!='\0'){temp+=a[i];}else{break;}}if(temp!="0"){unordered_map<string,int> isp,osp;isp["+"]=1;isp["-"]=1;isp["*"]=2;isp["/"]=2;osp["+"]=1;osp["-"]=1;osp["*"]=2;osp["/"]=2;double result=dispose(isp,osp,temp);printf("%.2f\n",result);temp.clear();}else{break;}}return 0; }總結
以上是生活随笔為你收集整理的1918 Problem A 简单计算器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 哪个软件测试手机电池续航好,14部手机电
- 下一篇: jcrop java_JAVA spri