简单计算器
来源:互联网 发布:对方qq网络状态准确吗 编辑:程序博客网 时间:2024/06/18 04:02
链接
#include<bits/stdc++.h>using namespace std;stack<int> num;stack<char> ope;int oppe(int num1,int num2,char op){ if(op=='+') return num1+num2; if(op=='-') return num1-num2; if(op=='*') return num1*num2; if(op=='/') return num1/num2; return 0;}void calculate(string str){ int len = str.length(); while(!num.empty()) num.pop(); while(!ope.empty()) ope.pop(); for(int i=0;i<len;i++){ if(str[i]>='0'&& str[i]<='9'){ int tmp = 0; while(str[i]>='0'&&str[i]<='9'&&i<len){ tmp = tmp*10 + str[i++]-'0'; } num.push(tmp); i--; }else{ if(str[i]==')'){ while(ope.top()!='('){ int num2 = num.top(); num.pop(); int num1 = num.top(); num.pop(); num.push(oppe(num1,num2,ope.top())); ope.pop(); } if(!ope.empty()) ope.pop(); } else if(str[i]=='(') ope.push(str[i]); else if(str[i]=='+'||str[i]=='-'){//考虑优先级,如果该字符是+、-则前一运算符可以计算,并将此运算符放入栈中,前面的均计算 while(!ope.empty()&&ope.top()!='('){ int num2 = num.top(); num.pop(); int num1 = num.top(); num.pop(); num.push(oppe(num1,num2,ope.top())); ope.pop(); } ope.push(str[i]); } else{ while(!ope.empty() && ope.top() == '*' && ope.top() == '/' ){ int num2 = num.top(); num.pop(); int num1 = num.top(); num.pop(); num.push(oppe(num1,num2,ope.top())); ope.pop(); } ope.push(str[i]); } } } while(!ope.empty()){ int num2 = num.top(); num.pop(); int num1 = num.top(); num.pop(); num.push(oppe(num1,num2,ope.top())); ope.pop(); } cout << num.top()<<endl;}int main(){ string str; cin >> str ; calculate(str);return 0;}
阅读全文
0 0
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- 简单计算器
- [ffmpeg]显示视频时长
- 2.创建窗口
- Conversion to Dalvik format failed with error 1 异常
- spring data使用
- [ffmpeg]显示视频尺寸
- 简单计算器
- 错误提示:apr-style L-file ERROR 5010
- (算法分析Week4)Count and Say[Easy]
- C语言之回调函数
- 《利用Python进行数据分析》--时间序列
- Windows环境下免安装版MySQL的配置方法
- 4大数据实战系列-hive安装配置优化
- Java课后简答题
- 15算法课程 27. Remove Element