1 + 2 4 + 2 * 5 - 7 / 11 0
3.00 13.36
分析:
题目难度:中等
解决方案:符号栈
难点:符号级别
c++代码如下:
#include <iostream> #include <stdio.h> #include <stack> #include <string.h> using namespace std; #define MAX_LEN 501 stack<double> num_stack; stack<char> sign_stack; char cs[MAX_LEN] ; int num_arr[MAX_LEN]; int n; int sign_arr[MAX_LEN]; int m; //判断符号 int isOp(char c){ return c=='+'||c=='-'||c=='*'||c=='/'; } //比较符号级别 int cmp(char o1,char o2){ if((o1=='/'||o1=='*')&&(o2=='+'||o2=='-'))return 1; return -1 ; } //单步运算 double op(char o,double a,double b){ double res = 0.0; if(o=='+')res = a+b; else if(o=='-')res = a - b; else if(o=='*')res = a * b; else res = a/b; return res ; } //主要函数计算表达式的结果 double getRes(){ int i=n-1,j=m-1; char t1,t2; double a,b,res ; num_stack.push(num_arr[i--]); sign_stack.push(sign_arr[j--]); while(!sign_stack.empty()){ if(i==-1&&j==-1){ t1 = sign_stack.top(); sign_stack.pop(); a = num_stack.top();num_stack.pop(); b = num_stack.top();num_stack.pop(); res = op(t1,a,b); num_stack.push(res); } if(i>=0){ num_stack.push(num_arr[i--]); } if(j>=0){ //关键!!! while(sign_stack.size()>0){ t1 = sign_stack.top(); t2 = sign_arr[j]; if(cmp(t1,t2)>0){ sign_stack.pop(); a =num_stack.top();num_stack.pop(); b =num_stack.top();num_stack.pop(); res = op(t1,a,b); num_stack.push(res); }else break; } sign_stack.push(sign_arr[j--]); } } res = num_stack.top() ;num_stack.pop(); return res ; } //表达式转化为两个数组 void cs2arr(){ int len = strlen(cs); int i ; int t = 0 ; n=0; m=0; for(i=0;1;i++){ if(isOp(cs[i])||cs[i]=='\0'){ if(isOp(cs[i]))sign_arr[m++] = cs[i]; num_arr[n++] = t; if(cs[i]=='\0')break; t = 0 ; } else if(cs[i]==' ')continue ; else { t*=10; t+=cs[i]-'0'; } } } int main() { while(1){ gets(cs); if(strcmp(cs,"0")==0)break; cs2arr(); printf("%.2lf\n",getRes()); } return 0; }
原文地址:http://blog.csdn.net/wwwzys/article/details/39161277