当前位置: 代码迷 >> 综合 >> 问题 A: 简单计算器
  详细解决方案

问题 A: 简单计算器

热度:59   发布时间:2023-09-22 10:15:02.0

题目描述

读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。

输入

测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。

输出

对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。

样例输入

30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0

样例输出

12178.21
#include<stdio.h>
#include<string.h>
#include<cstdio>
#include<map>
#include<queue>
#include<iostream>
#include<stack>
#include<string>
using namespace std;
struct node{double num;char op;bool flag;
};string s;
map<char,int>op;
queue<node> q;
stack<node>sta;
void change(){double num;node temp;for(int i=0;i<s.length();){if(s[i]>='0'&&s[i]<='9'){temp.flag=true;temp.num=s[i++]-'0';while(i<s.length()&&s[i]>='0'&&s[i]<='9'){temp.num=temp.num*10+s[i]-'0';i++;}q.push(temp);}else{temp.flag=false;while(!sta.empty()&&op[s[i]]<=op[sta.top().op]){q.push(sta.top());sta.pop();}temp.op=s[i];sta.push(temp);i++;}} while(!sta.empty()){q.push(sta.top());sta.pop();}
}
double cal()
{double temp1,temp2;node temp,cur;while(!q.empty()){cur=q.front();q.pop();if(cur.flag==true)sta.push(cur);else{temp1=sta.top().num;sta.pop();temp2=sta.top().num;sta.pop();if(cur.op=='+')temp.num=temp1+temp2;else if(cur.op=='-')temp.num=temp2-temp1;else if(cur.op=='*')temp.num=temp1*temp2;else if(cur.op=='/')temp.num=temp2/temp1;temp.flag=true;sta.push(temp);}}return sta.top().num;
}
int main()
{op['+']=op['-']=1;op['/']=op['*']=2;while(getline(cin,s)&&s!="0"){for(string::iterator it=s.begin();it!=s.end();it++){if(*it==' ')s.erase(it);}while(!sta.empty())sta.pop();change();printf("%.02lf\n",cal());}return 0;	
}

 

  相关解决方案