제목 설명
+,-, *, / 만 포함 된 음이 아닌 정수 계산 식을 읽고 식의 값을 계산합니다.
시작하다
테스트 입력에는 여러 테스트 케이스가 포함되어 있으며 각 테스트 케이스는 한 행을 차지하고 각 행은 200자를 초과하지 않으며 정수와 연산자는 공백으로 구분됩니다. 불법적 인 표현이 없습니다. 행에 0 만 있으면 입력이 종료되고 해당 결과가 출력되지 않습니다.
산출
각 테스트 케이스, 즉 표현식 값에 대해 소수점 2 자리까지 정확하게 1 줄을 출력합니다.
샘플 입력 복사
30 / 90-26 + 97-5-6-13 / 88 * 6 + 51/29 + 79 * 87 + 57 * 92 0
샘플 출력 복사
12178.21
문제 해결 아이디어 :
1. 접미사 식에서 접미사 식으로
2. 접미사 식 계산
#include <iostream>
#include <cstdio>
#include <queue>
#include <stack>
#include <map>
using namespace std;
struct node
{
double data;
char ch;
int flag;
};
queue <node> q;
stack <node> s;
map<char,int> m;
string str;
void init()
{
while(!s.empty()) s.pop();
}
void change()///中缀转后缀
{
node t;
int n=str.size();
double cnt=0.0;
for(int i=0;i<n;i++){
if(str[i]>='0'&&str[i]<='9'){
cnt=cnt*10+str[i]-'0';
}
else if(str[i]!=' '){
t.flag=1;
t.data=cnt;
q.push(t);
cnt=0.0;
while(!s.empty()&&m[s.top().ch]>=m[str[i]]){
q.push(s.top());
s.pop();
}
t.flag=0;
t.ch=str[i];
s.push(t);
}
}
t.flag=1;
t.data=cnt;
q.push(t);
while(!s.empty()){
q.push(s.top());
s.pop();
}
}
void cal()///计算后缀表达式的值
{
node t;
while(!q.empty())
{
t=q.front();
q.pop();
if(t.flag==1) s.push(t);
else{
node x=s.top();s.pop();
node y=s.top();s.pop();
if(t.ch=='*') y.data*=x.data;
if(t.ch=='/') y.data/=x.data;
if(t.ch=='+') y.data+=x.data;
if(t.ch=='-') y.data-=x.data;
s.push(y);
}
}
double ans=s.top().data;
printf("%.2lf\n",ans);
}
int main()
{
m['+']=1;m['-']=1;
m['*']=2;m['/']=2;
while(getline(cin,str),str!="0"){
init();
change();
cal();
}
return 0;
}