hdu 1237 简单计算器有感
2010-08-03 14:31
417 查看
话说在数据结构上看完之后就来敲了这题,敲完提交后wa于是找错,发现没考虑0 + 1这种数据,直接跳出了,于是改了后来还是wa,于是我又查,发现1 - 2 + 4输出的是-5违反了操作符优先级相同从左往右运算的原则,后来发现1 / 2 / 3 * 2 * 3这组也错了,于是看了书,发现是书上的优先级表错了于是改之就过了,这个代码稍作修改就能适用于带括号的运算
同时给几组比较容易错的吧
0 + 1
1.00
1
1.00
1 - 2 + 4
3.00
1 * 2 + 1 + 1 * 2 * 3 / 3 - 1 + 2 / 1
6.00
1 / 2 / 3 * 2 * 3
1.00
下面是代码,希望帮到你们
同时给几组比较容易错的吧
0 + 1
1.00
1
1.00
1 - 2 + 4
3.00
1 * 2 + 1 + 1 * 2 * 3 / 3 - 1 + 2 / 1
6.00
1 / 2 / 3 * 2 * 3
1.00
下面是代码,希望帮到你们
#include<iostream> #include<stack> #include<cctype> #include<string> #include<map> using namespace std; const int Max=220; char You[8][8]={ {' ',' ',' ',' ',' ',' ',' ',' '} ,{' ','<','<','<','<','<','>','>'} ,{' ','<','<','<','<','<','>','>'} ,{' ','>','>','<','<','<','>','>'} ,{' ','>','>','<','<','<','>','>'} ,{' ','<','<','<','<','<','=',' '} ,{' ','>','>','>','>',' ','>','>'} ,{' ','<','<','<','<','<',' ','='}}; double opera(double a,double b,char op) { switch(op) { case '-':return a-b; case '+':return a+b; case '*':return a*b; case '/':return a/b; } return 0; } double Oper(string chuchun[Max],int len) { map<char,int> Map; Map['+']=1; Map['-']=2; Map['*']=3; Map['/']=4; Map['(']=5; Map[')']=6; Map['#']=7; stack<char> optr; stack<double > optd; int i,j; optr.push('#'); for(i=0;i<len;i++) { if(isdigit(chuchun[i][0])) { int temp=1; int sum=0; for(j=chuchun[i].size()-1;j>=0;j--) { sum+=(chuchun[i][j]-'0')*temp; temp*=10; } optd.push(sum); } else { bool on_off=true; while(on_off) { char op=optr.top(); if(optr.size()==0) break; switch(You[Map[chuchun[i][0]]][Map[op]]) { case '<': { optr.pop(); double a=optd.top(); optd.pop(); double b=optd.top(); optd.pop(); double res=opera(b,a,op); optd.push(res); }break; case '=': { optr.pop(); on_off=false; }break; case ' ': case '>': { optr.push(chuchun[i][0]); on_off=false; }break; } } } } return optd.top(); } int saveword(string str[Max],string & Now) { int len=0; while(Now.find(" ")!=string::npos) { int now=Now.find(" "); str[len++]=Now.substr(0,now); Now.erase(0,now); while(Now[0]==' ') Now.erase(Now.begin()); } if(Now.size()!=0) str[len++]=Now; return len; } int main() { string str; string chuchun[Max]; while(getline(cin,str)) { if(str.size()==1&&str[0]=='0') break; int Len=str.size(); int len; len=saveword(chuchun,str); chuchun[len++]="#"; double ch=Oper(chuchun,len); printf("%.2lf/n",ch); } return 0; }
相关文章推荐
- 【HDU】-1237-简单计算器(栈)
- hdu 1237 简单计算器 (栈的简单应用)
- HDU_1237_简单计算器
- hdu 1237 简单计算器(数组模拟栈,队列)
- HDU 1237 简单计算器 (栈 )
- hdu 1237 简单计算器
- HDU 1237 简单计算器
- hdu 1237 简单计算器
- hdu 1237 简单计算器
- HDU-1237-简单计算器
- hdu - 1237 - 简单计算器
- HDU 1237 简单计算器 && 字符串模拟四则运算
- hdu 1237 简单计算器
- hdu 1237 简单计算器
- 【STL基础03】HDU-1237-简单计算器
- HDU 1237 简单计算器(栈)
- [JAVA][HDU 1237][九度 1019][简单计算器]
- hdu 1237简单计算器
- HDU 1237-简单计算器
- HDU-1237-简单计算器