02-线性结构3. 求前缀表达式的值(25)

时间限制
400 ms
内存限制
65536 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<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
#include<string>
#include<stack>
using namespace std;
int main(){
//freopen("D:\\input.txt","r",stdin);
stack<double> fi;
stack<string> input;
string s; //bool can=true;
while(cin>>s){
input.push(s);
}
while(!input.empty()){
s=input.top();
input.pop();
if(s.length()==&&!(s[]>=''&&s[]<='')){
double a=fi.top();
fi.pop();
double b=fi.top();
fi.pop();
switch(s[]){
case'+':{
//cout<<"+: "<<a+b<<endl;
fi.push(a+b);
break;
}
case'-':{
//cout<<"-: "<<a-b<<endl;
fi.push(a-b);
break;
}
case'*':{
//cout<<"*: "<<a*b<<endl;
fi.push(a*b);
break;
}
case'/':{
if(b==){
printf("ERROR\n");
//can=false;
return ;
}
//cout<<"/: "<<a/b<<endl;
fi.push(a/b);
break;
}
default:{
printf("ERROR\n");
return ;
}
}
}else if((s[]>=''&&s[]<='')||(s.length()>&&!(s[]>=''&&s[]<='')&&(s[]>=''&&s[]<=''))){
double cal=;
int i=;
if(s[i]=='+'||s[i]=='-'){
if(s[i]=='-'){
cal=-;
}
i++;
}
double intpart=,decpart=;
while(i<s.length()&&s[i]!='.'){//注意换算
intpart*=;
intpart+=s[i++]-'';
}
i++;
int j;
for(j=s.length()-;j>=i;j--){
decpart+=s[j]-'';
decpart*=0.1;
}
fi.push(cal*(intpart+decpart));
}else{
printf("ERROR\n");
return ;
}
}
//cout<<fi.top()<<endl; printf("%.1lf\n",fi.top());
return ;
}

最新文章

  1. sublime text 3 + python配置,完整搭建及常用插件安装
  2. spring boot(五):spring data jpa的使用
  3. Bootstrap&lt;基础十四&gt; 按钮下拉菜单
  4. DSP(1) -- 离散时间信号的序列类型
  5. css+js定位到屏幕中间
  6. 测试方法---&quot;SFDIPOT&quot;
  7. radio checked不起作用的原因
  8. ZZTHX-注意点
  9. 在DDMS中访问data目录
  10. @repository注解
  11. Course Schedule ——LeetCode
  12. Debugging Failed Because Integrated Windows Authentication Is Not Enabled
  13. sql发邮件
  14. Linux完全卸载Oracle的操作步骤
  15. Create Oracle database using dbca in silent mode
  16. ES6躬行记(4)——模板字面量
  17. java基础----&gt;String中replace和replaceAll方法
  18. 【转】Java生成图片验证码
  19. 【vim】保存文件并退出 :w=:wq
  20. C# xml 常规 保护 方法总结

热门文章

  1. windows phone制作引导页
  2. Windows下查看进程状态/信息
  3. shell和matlab之间的参数传递
  4. PS基本操作汇总(持续更新)
  5. PHP选项和运行
  6. Resurrectio-capserjs的自动化脚本录制工具
  7. 跟我一起读postgresql源码(四)——Planer(查询规划模块)(上)
  8. [AHOI2009]中国象棋 BZOJ1801 dp
  9. C++_语法知识点大纲
  10. rest-assured之静态导入及简单使用实例