pat02-线性结构3. 求前缀表达式的值(25)
2024-08-30 20:31:47
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 ;
}
最新文章
- sublime text 3 + python配置,完整搭建及常用插件安装
- spring boot(五):spring data jpa的使用
- Bootstrap<;基础十四>; 按钮下拉菜单
- DSP(1) -- 离散时间信号的序列类型
- css+js定位到屏幕中间
- 测试方法---";SFDIPOT";
- radio checked不起作用的原因
- ZZTHX-注意点
- 在DDMS中访问data目录
- @repository注解
- Course Schedule ——LeetCode
- Debugging Failed Because Integrated Windows Authentication Is Not Enabled
- sql发邮件
- Linux完全卸载Oracle的操作步骤
- Create Oracle database using dbca in silent mode
- ES6躬行记(4)——模板字面量
- java基础---->;String中replace和replaceAll方法
- 【转】Java生成图片验证码
- 【vim】保存文件并退出 :w=:wq
- C# xml 常规 保护 方法总结