计算器 表达式求值
来源:互联网 发布:mac 装win10 鼠标右键 编辑:程序博客网 时间:2024/06/02 03:29
整数小数均可,支持加减乘除乘方,表达式中可加空格,最后输不输入等号都行。
#include <cstdio>#include <cstring>#include <cmath>#include <stack>using namespace std;#define N 100char s[N];int length, i;stack<double> num;stack<char> op;double calc(double a, char o, double b){switch (o){case '+': return a + b;case '-': return a - b;case '*': return a * b;case '/': return a / b;case '^': return pow(a, b);}}int pro(char o){switch (o){case '#': return -1;case '+':case '-': return 1;case '*':case '/': return 2;case '^': return 3;case '(': return 0;}}double getNumber(){char number[N];int j = 0;while ((i < length) && (s[i] >= '0' && s[i] <= '9' || s[i] == '.')) number[j++] = s[i++];number[j] = '\0';return atof(number);}void back(){double b = num.top(); num.pop();double a = num.top(); num.pop();char o = op.top(); op.pop();num.push(calc(a, o, b));}double calculate(){op.push('#');length = strlen(s);i = 0;while (i < length){if (s[i] >= '0' && s[i] <= '9'){num.push(getNumber());continue;}switch (s[i]){case ' ': i++; break;case '(': op.push(s[i++]); break;case ')': while (op.top() != '(')back();op.pop();i++;break;case '=':case '\n':while (op.top() != '#') back();return num.top();default:while (pro(op.top()) >= pro(s[i])) back();op.push(s[i++]);}}}int main(){fgets(s, sizeof(s), stdin);printf("%lf\n", calculate());return 0;}
0 0
- 计算器 表达式求值 数据结构
- 计算器 表达式求值
- js实现计算器 提供算术表达式求值
- hdu 1237 简单计算器(表达式求值)
- HDU 1237 简单计算器 表达式求值
- 表达式求值(简易计算器的核心)
- 具有表达式求值功能的计算器软件设计
- 简单计算器求值(中缀表达式转化成后缀表达式)
- 计算器制作JAVA版(第三步,表达式求值(+-*/))
- 利用SLR实现可编程计算器(表达式求值)
- HDU 1237(简单计算器)栈的应用-表达式求值
- hdu 1237 简单计算器【最简单的表达式求值】
- [计蒜客 15504 百度的科学计算器(简单)]表达式求值
- HDU 1237 简单计算器(中缀表达式求值)
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 《Java程序设计》课程实验指导书程序代码(答案)(实验七)
- hdu 4123 rmq与树的直径
- pixhawk 整体架构的认识
- 一些算法总结
- windows和linux下VTK7.0.0的配置
- 计算器 表达式求值
- Android之BLE开发(一)
- NSTimer的5种创建方法异同
- Ajax中window.location.href无法跳转的解决办法
- hdu 4122 单调队列或线段树
- 程序未动, 内存先行. (研发)
- MUI 按两次返回键退出应用 及 地理位置获取
- 古典密码学笔记
- 作业——在线学习Android课程之第十五周(设计模式二)