3-07. 求前綴表達式的值(25)
時間限制
400 ms
內存限制
32000 kB
代碼長度限制
8000 B
判題程序
Standard
算術表達式有前綴表示法、中綴表示法和後綴表示法等形式。前綴表達式指二元運算符位於兩個運算數之前,例如2+3*(7-4)+8/4的前綴表達式是:+ + 2 * 3 - 7 4 / 8 4。請設計程序計算前綴表達式的結果值。
輸入格式說明:
輸入在一行內給出不超過30個字符的前綴表達式,只包含+、-、*、\以及運算數,不同對象(運算數、運算符號)之間以空格分隔。
輸出格式說明:
輸出前綴表達式的運算結果,精確到小數點後1位,或錯誤信息“ERROR”。
樣例輸入與輸出:
序號 | 輸入 | 輸出 |
1 |
+ + 2 * 3 - 7 4 / 8 4 |
13.0 |
2 |
/ -25 + * - 2 3 4 / 8 4 |
12.5 |
3 |
/ 5 + * - 2 3 4 / 8 2 |
ERROR |
4 |
+10.23 |
10.2 |
#include<stdio.h>
#include<stack>
#include<iostream>
#include<string>
using namespace std;
float oper(float f1,float f2, char op)
{
if(op=='+')
return f1+f2;
else if(op=='-')
return f1-f2;
else if(op=='*')
return f1*f2*1.0;
else if(op=='/')
return f1*1.0/f2;
}
int main()
{
stack<float> s;
string prefixExp;
getline(cin,prefixExp);
int strLen=prefixExp.length();
int temp,i,j;
int t1,t2;
for(i=strLen-1;i>=0;i--)
{
string digitStr="";
if(prefixExp[i]=='+' || prefixExp[i]=='-' || prefixExp[i]=='*' || prefixExp[i]=='/') //運算符
{
t1=s.top();
s.pop();
t2=s.top();
s.pop();
if(t2==0 && prefixExp[i]=='/')
{
printf("ERROR\n");
return 0;
}
s.push(oper(t1,t2,prefixExp[i]));
// printf("%f\n",s.top());
i--;//下一位肯定是空格
}
else //運算數
{
while(i>=0 && prefixExp[i]!=' ') //不要漏掉i>=0條件
{
digitStr=prefixExp[i]+digitStr;
i--;
}
//printf("atof:%f\n",atof(digitStr.c_str()));
s.push(atof(digitStr.c_str()));
}
}
if(s.size()==1)
printf("%0.1f\n",s.top());
else
printf("ERROR\n");
return 0;
}