后缀数求值

来源:互联网 发布:淘宝买演唱会门票骗局 编辑:程序博客网 时间:2024/06/16 20:43

后缀数求值:

 


后缀表达式求值的算法:

step1:设置一个空栈;

step2:从左到右扫描这个栈;

step3; 如遇到操作数则入栈,若遇到运算符则从栈中退出两个元素(退一个出栈一次);

step4:先退出的元素放在运算符右边,后退出的元素放到运算符左边;

strp5:运算结果入栈;

step6:回到step2,直到遍历完表达式 (循环





===================================================

表达式:3+(2-5)*6/3

后缀表达式:3 2 5 - 6 3 / * +




#include<cstdio>#include<cstdlib>#include<stack>#include<cstring>#include<algorithm>//#include<windows.h>using namespace std;int main(){stack<char> s;                  //定义的字符栈char str[100];printf("plese enter a suffix expression:");scanf("%s", str);while (!s.empty())s.pop();               //栈不为空,出栈;int i = 0;while (str[i] != '\0'){if (str[i] >= '0'&&str[i] <= '9'){s.push(str[i] - 48);      // s.push(str[i]-'0 ’); ‘9'=57 因为数字的ascii码是连续的所以'9'-'0'=57-48=9}else if (str[i] == '+'){int m = s.top();s.pop();              //不要忘记int n = s.top();s.pop();              //出栈s.push(n + m);}else if (str[i] == '-'){int m = s.top();s.pop();int n = s.top();printf("%d", n);s.pop();}else if (str[i] == '*'){int m = s.top();s.pop();int n = s.top();s.pop();s.push(n* m);}else if (str[i] == '/'){int m = s.top();s.pop();int n = s.top();s.pop();s.push(n /m);}i++;}printf("%d", s.top());printf("\n");//system("pause");return 0;}


原创粉丝点击