简单计算器(递归写法)
来源:互联网 发布:网络舞曲最红 编辑:程序博客网 时间:2024/04/28 15:48
暑假集训练手一发: http://acm.hust.edu.cn/vjudge/contest/view.action?cid=83171#overview
Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 24 + 2 * 5 - 7 / 110
思想很简单:递归处理,先做乘除!(写的很挫)
// http://acm.hust.edu.cn/vjudge/contest/view.action?cid=83171#overview#include<iostream>#include<cstdio>#include<algorithm>#include<queue>#include<vector>#include<cstring>using namespace std;vector <double> IQ;vector <char> CQ;double solve(int p){ //if(p==IQ.size()-1)return IQ[p]; //if(CQ[p]=='+')return IQ[p]+solve(p+1); //if(CQ[p]=='-')return IQ[p]-solve(p+1); double x = IQ[p]; while((p<IQ.size()-1)&&(CQ[p]=='*'||CQ[p]=='/')){ if(CQ[p]=='*')x=x*IQ[p+1]; if(CQ[p]=='/')x=x/IQ[p+1]; p++; } if(p==IQ.size()-1)return x; if(CQ[p]=='+')return x+solve(p+1); if(CQ[p]=='-'){ int q = p+1; while(q<CQ.size()){ if(CQ[q]=='+')CQ[q]='-'; else if(CQ[q]=='-')CQ[q]='+'; q++; } return x-solve(p+1); }}int main(){ char str[222]; while(gets(str),strcmp(str,"0")!=0){// puts(str); int len = strlen(str); IQ.clear(); CQ.clear(); for(int i=0;i<len;i++){ int x=0; bool flag = false; while(i<len&&isdigit(str[i])){ x=x*10+str[i]-'0'; i++; flag = true; } if(flag) IQ.push_back(x*1.0); else CQ.push_back(str[i++]); }// cout<<IQ.size()<<endl;// for(int i=0;i<IQ.size();i++)cout<<IQ[i]<<" ";cout<<endl;// cout<<CQ.size()<<endl;// for(int i=0;i<CQ.size();i++)cout<<CQ[i]<<"";cout<<endl; double ans = solve(0); printf("%.2lf\n",ans); } return 0;}
0 0
- 简单计算器(递归写法)
- 算法学习之递归--表达式计算(简单计算器)
- 简单计算器(java)
- 简单计算器(应用软件)
- hloj1184(简单计算器)
- 简单计算器(栈)
- hdoj 1237 简单计算器(计算器应用)
- C#实现计算器(简单计算器)
- python 简单计算器递归算法 多层括号处理
- imagerloader(简单写法)
- SQL 中的尖括号">"自动转成>,SQL递归简单写法
- 简单的计算器(java)
- 简单计算器(hdu 1237)
- 简单计算器(不支持括号)
- 《简单计算器实现(c#)》
- Unity3d 简单计算器(OnGUI)
- 简单计算器(hdu 1237)
- 简单计算器(objective-c)
- 多客户端上传服务器文档使用scp命令不需要输入密码
- OpenCV学习:将图像转为二值图像(函数cvtColor和函数threshold)
- 为eclipse离线安装hibernate tools插件
- Algorithms—150.Evaluate Reverse Polish Notation
- Github上README.md介绍 语法
- 简单计算器(递归写法)
- 字符串转换成数字以及注意事项
- 1+2+3+......+n
- ProtocolBuffer for Objective-C 运行环境配置(真正测试过的3.0版本编译)
- AndroidJNI.SetObjectField 设置对象域
- POJ 3186
- 希尔排序法
- 【weiphp】微官网分类列表地址获取说明
- [剑指offer]8.重建二叉树