逆波兰式与表达式求解

来源:互联网 发布:光纤数据采集卡 编辑:程序博客网 时间:2024/05/19 22:52
/***************逆波兰式即后缀表示法  预处理 ———— 中序表达式 - > 逆序表达式(infix to postfix)算法:while (表达式非空)if (遇到操作数)直接输出else if (遇到操作符op)op是(直接入栈sop是) s.push输出,直到(op是四则运算,则while (1)if (s为空 || s.top为(|| op 优先级高于 s.top)op 入栈break;elses.push输出while (!s.empty)s.push输出计算算法 :if (遇到操作数)入栈selse (遇到操作符)        s.push两个元素进行运算,结果入栈*******************/#include <iostream>#include <stack>#include <cstring>#include <string>#include <cstdio>using namespace std;stack<char> op_flag;stack<double> result;double Result(char *s){double tmp, a, b;while ('\0' != *s){if (*s >= '0' && *s <= '9' || '.' == *s){sscanf(s, "%lf", &tmp);while (*s >= '0' && *s <= '9' || '.' == *s)++s;result.push(tmp);}else if (NULL != strchr("+/-*", *s)){b = result.top();result.pop();a = result.top();result.pop();if ('+' == *s)result.push(a + b);else if ('-' == *s)result.push(a - b);else if ('*' == *s)result.push(a*b);else if ('/' == *s)result.push(a / b);++s;}else++s;}return result.top();}void Get_after(char *s, char *re){while ('\0' != *s){if (NULL != strchr("0123456789.", *s)){*re++ = *s;}else{if ('(' == *s){op_flag.push((char)*s);}else if (')' == *s){while ('(' != op_flag.top()){*re++ = ' ';*re++ = op_flag.top();op_flag.pop();}op_flag.pop();}else if (NULL != strchr("*-+/", *s)){while (1){*re++ = ' ';if (op_flag.empty() || '(' == op_flag.top()|| (NULL != strchr("+-", op_flag.top()) && NULL != strchr("*/", *s))){op_flag.push((char)*s);break;}else{*re++ = op_flag.top();op_flag.pop();}}}}s++;}while (!op_flag.empty()){*re++ = ' ';*re++ = op_flag.top();op_flag.pop();}*re = '\0';}int main(){char s[1000], re[1000];printf("本计算器支持四则运算和括号以及小数运算,请输入正确表达式,以防崩溃\n");while (1){while (!op_flag.empty())op_flag.pop();while (!result.empty())result.pop();printf("输入表达式:");gets(s);Get_after(s, re);printf("结果:%.2lf\n", Result(re));}return 0;}

0 0
原创粉丝点击