博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
计算表达值模板
阅读量:7239 次
发布时间:2019-06-29

本文共 2308 字,大约阅读时间需要 7 分钟。

namespace cal_expression{    int level[300];    bool f;    ///设置优先级    inline void init() {        level['*'] = level['/'] = 2;        level['+'] = level['-'] = 1;        f = true;    }    ///加空格    inline string add_blank(string s) {        string t;        for (int i = 0; i < s.size(); ++i) {            if(isdigit(s[i])) t += s[i];            else {                t += ' ';                t += s[i];                t += ' ';            }        }        return t;    }    inline string convert(string s) {  // 把中缀表达式转换为后缀表达式      stack
oper; stringstream ss; ss << s; string t, tmp; while (ss >> tmp) { if (isdigit(tmp[0])) t += tmp + " "; // 1. 如果遇到一个数,输出该数 else if (tmp[0] == '(') oper.push(tmp[0]); // 2. 如果遇到左括号,把左括号入栈 else if (tmp[0] == ')') { // 3. 如果遇到右括号, while (!oper.empty() && oper.top() != '(') t += string(1, oper.top()) + " ", oper.pop(); // 不断取出栈顶并输出,直到栈顶为左括号, oper.pop(); // 然后把左括号出栈 } else { // 4. 如果遇到运算符 while (!oper.empty() && level[oper.top()] >= level[tmp[0]]) t += string(1, oper.top()) + " ", oper.pop(); // 只要栈顶符号的优先级不低于新符号,就不断取出栈顶并输出 oper.push(tmp[0]); // 最后把新符号进栈 } } while (!oper.empty()) t += string(1, oper.top()) + " ", oper.pop(); return t; } inline int calc(string s) { // 计算转换好的后缀表达式 stack
num; stringstream ss; ss << s; string t, tmp; while (ss >> tmp) { if (isdigit(tmp[0])) num.push(stoi(tmp)); else { int b, a; // 取出栈顶元素,注意顺序 if (!num.empty()) b = num.top(); num.pop(); if (!num.empty()) a = num.top(); num.pop(); if (tmp[0] == '+') num.push(a + b); if (tmp[0] == '-') num.push(a - b); if (tmp[0] == '*') num.push(a * b); if (tmp[0] == '/') { if(b && a%b == 0) num.push(a / b); else num.push(555), f = false; } } } return num.top(); } inline int solve(string s) { init(); int v = calc(convert(add_blank(s))); if(f) return v; else return -1; }}

 

转载于:https://www.cnblogs.com/widsom/p/10887142.html

你可能感兴趣的文章
OpenCV学习(9) 分水岭算法(3)
查看>>
Android WebView漏洞(转)
查看>>
ExtJS4.2:自定义主题 入门
查看>>
【Android】事件输入系统-代码层次解读
查看>>
js 对文件操作
查看>>
MySQL 5.6学习笔记(数据表基本操作)
查看>>
复制控制---复制构造函数
查看>>
bash把所有屏幕输出重定向到文件并保持屏幕输出的方法
查看>>
HBase 压缩算法设置及修改
查看>>
深入了解jquery中的键盘事件
查看>>
windows常用命令行整理
查看>>
DotNet中人民币符号的输出
查看>>
Spark源码分析 – SchedulerBackend
查看>>
正则表达式
查看>>
C语言中结构体 自引用 和 相互引用
查看>>
awk substr()函数
查看>>
git diff的用法
查看>>
[SQL基础]入门
查看>>
s3cmd 安装使用指南
查看>>
hdu 1253:胜利大逃亡(基础广搜BFS)
查看>>