运行:

(a+b)*c
后缀表达式:ab+c*
赋值:
Enter the a : 10
Enter the b : 3
Enter the c : 5
结果为:65

代码是我从的逻辑判断系统改过来的,可进行扩展或者修改

注意:1、适用变量为单字符。

2、表达式不含空格

PS:如果想让变量为多字符(字符串),那么变量与变量、变量与运算符之间应该用空格分开

#include<iostream>
#include<map>
#include<string>
#include<stack>
#include<vector>
using namespace std;
class Logic {
public:
Logic() {} //构造函数
void Load(string); //input
int priority(char); //获取运算符优先级
string trans(string); //中缀式->后缀式
double calculate(); //逻辑判断
void V_assign(); //变量赋值
string M_exp; //中缀式
string P_exp; //后缀式
map<string, double> variate; //赋值序列
};
void Logic::Load(string str) {
M_exp = str;;
P_exp = trans(M_exp); //处理数据(表达式转换)
}
int Logic::priority(char ch) {
if (ch == '*'||ch=='/')
return 2;
if (ch == '+'||ch=='-')
return 1;
if (ch == '(')
return -1;
return 0;
}
double Logic::calculate() {
string operators("+-*/");
stack<double> res; //此栈用作运算
double a, b;
for (int i = 0; i<P_exp.length(); i++) {
if (operators.find(P_exp[i]) == string::npos) { //遇到操作数,根据“字典”翻译后入栈
res.push(variate[P_exp.substr(i, 1)]);
}
else {
switch (P_exp[i]) {
case '+':
a = res.top();
res.pop();
b = res.top();
res.pop();
res.push(a + b);
break;
case '*':
a = res.top();
res.pop();
b = res.top();
res.pop();
res.push(a * b);
break;
case '-':
a = res.top();
res.pop();
b = res.top();
res.pop();
res.push(b-a);
break;
case '/':
a = res.top();
res.pop();
b = res.top();
res.pop();
res.push(b/a);
break;
}
}
}
return res.top();
}
string Logic::trans(string m_exp) {
string p_exp;
stack<char> stk;
string operators("+-*/(");
for (int i = 0; i < m_exp.length(); i++) {
string one;
if (operators.find(m_exp[i]) != string::npos) { //出现操作符
if (m_exp[i] == '(') //栈中添加左括号
stk.push(m_exp[i]);
else { //操作符的优先级判断
while ((!stk.empty()) && (priority(m_exp[i]) <= priority(stk.top()))) { //当栈不为空时,进行优先级判断
p_exp.push_back(stk.top()); //若当前操作符优先级低于栈顶,弹出栈顶,放到后缀式中
stk.pop();
}
stk.push(m_exp[i]); //将当前操作符入栈
}
}
else if (m_exp[i] == ')') { //出现右括号时,将栈中元素一直弹出,直至弹出左括号
while (stk.top() != '(') {
p_exp.push_back(stk.top());
stk.pop();
}
stk.pop(); //弹出左括号
}
else { //把操作数加入到后缀式中
variate[m_exp.substr(i, 1)] = 0;
p_exp.push_back(m_exp[i]);
} }
while (!stk.empty()) { //将栈中剩余操作符放到后缀式中
p_exp.push_back(stk.top());
stk.pop();
}
return p_exp;
}
void Logic::V_assign() { //公式赋值
int i = 0;
for (auto it = variate.begin(); it != variate.end(); it++) {
cout << "Enter the " << it->first << " : ";
cin >> it->second;
}
}
int main() {
Logic my;
string str;
cin >> str;
my.Load(str);
cout << "后缀表达式:" << my.P_exp << endl;
cout << "赋值:" << endl;
my.V_assign();
cout<<"结果为:"<<my.calculate();
return 0;
}

JAVA:

import java.util.Scanner;
public class Calculate {
String m_exp=new String() ,p_exp=new String();
int result=0;
public Calculate(String exp) {
m_exp=exp;
}
int counter(){
int stk[]=new int[100],a,b;
int top=-1;
for(int i=0;i<p_exp.length();i++){
if(p_exp.charAt(i)>='0'&&p_exp.charAt(i)<='9'){
stk[++top]=Character.getNumericValue(p_exp.charAt(i));
}
else{
switch (p_exp.charAt(i)) {
case '+':
a = stk[top--];
b = stk[top--];
stk[++top]=a+b;
break;
case '*':
a = stk[top--];
b = stk[top--];
stk[++top]=a*b;
break;
case '-':
a = stk[top--];
b = stk[top--];
stk[++top]=b-a;
break;
case '/':
a = stk[top--];
b = stk[top--];
if(a==0)
return 1;
stk[++top]=b/a;
break;
} }
} if(top!=0)
return 1;
result=stk[0];
return 0;
}
String trans(){
char stk[]=new char[100];
int top=-1;
String operators=new String("+-*/("); for (int i = 0; i < m_exp.length(); i++) {
if (operators.indexOf(m_exp.charAt(i)) != -1) { //出现操作符
if (m_exp.charAt(i) == '(') //栈中添加左括号
stk[++top]=m_exp.charAt(i);
else { //操作符的优先级判断
while ((top>=0) && (priority(m_exp.charAt(i)) <= priority(stk[top]))) { //当栈不为空时,进行优先级判断
p_exp+=stk[top--]; //若当前操作符优先级低于栈顶,弹出栈顶,放到后缀式中
}
stk[++top]=(m_exp.charAt(i)); //将当前操作符入栈
}
}
else if (m_exp.charAt(i) == ')') { //出现右括号时,将栈中元素一直弹出,直至弹出左括号
while (stk[top] != '(') {
p_exp+=stk[top--];
}
top--; //弹出左括号
}
else { //把操作数加入到后缀式中
p_exp+=m_exp.charAt(i);
} }
while (top>=0) { //将栈中剩余操作符放到后缀式中
p_exp+=stk[top--];
}
return p_exp;
}
int priority(char ch){
if (ch == '*'||ch=='/')
return 2;
if (ch == '+'||ch=='-')
return 1;
if (ch == '(')
return -1;
return 0;
}
public static void main(String []args){ //TEST
Scanner input=new Scanner(System.in);
Calculate my=new Calculate(input.next());
my.trans(); //后缀试转换
if(my.counter()==1)
System.out.println("ERROR");
else
System.out.println(my.result);
} }

计算器类(C++&JAVA——表达式转换、运算、模板公式)的更多相关文章

  1. java.util.Date日期类通过java语句转换成Sql(这里测试用的是oracle)语句可直接插入(如:insert into)的日期类型

    public void add(Emp emp) throws Exception{ QueryRunner runner = new QueryRunner(JdbcUtil.getDataSour ...

  2. java的大数运算模板

    import java.math.BigInteger; import java.util.Scanner; public class Main { public static void main(S ...

  3. Java初学者作业——定义一个计算器类, 实现计算器类中加、 减、 乘、 除的运算方法, 每个方法能够接收2个参数。

    返回本章节 返回作业目录 需求说明: 定义一个计算器类, 实现计算器类中加. 减. 乘. 除的运算方法, 每个方法能够接收2个参数. 实现思路: 定义计算器类. 定义计算器类中加.减.乘.除的方法. ...

  4. C++做四则运算的MFC计算器(二)栈转换和计算后缀表达式

    上篇写了MFC界面搭建,这篇就写实现计算.涉及到数据结构,对新手很不友好. 虽然是MFC程序,但是能灵活地分离后台代码,自行构建控制台程序. 上篇文章链接:C++做四则运算的MFC计算器(一)MFC界 ...

  5. 利用JAXB实现java实体类和xml互相转换

    1.应用场景 在使用WebService实现数据上传下载,数据查询时,可以利用JAXB实现java实体类和xml互相转换 2.Demo 2.1 student.java 实体类,包含list(set同 ...

  6. Java中int类型和tyte[]之间转换及byte[]合并

    JAVA基于位移的 int类型和tyte[]之间转换 [java] view plaincopy /** * 基于位移的int转化成byte[] * @param int number * @retu ...

  7. 我的Android进阶之旅------>Java文件大小转换工具类 (B,KB,MB,GB,TB,PB之间的大小转换)

    Java文件大小转换工具类 (B,KB,MB,GB,TB,PB之间的大小转换) 有时候要做出如下所示的展示文件大小的效果时候,需要对文件大小进行转换,然后再进行相关的代码逻辑编写. 下面是一个Java ...

  8. 用MyEclipse将java文件转换成UML类图

    用MyEclipse将java文件转换成UML类图 参考: 用MyEclipse将java文件转换成UML类图 - 君临天下的博客 - CSDN博客  http://blog.csdn.net/dan ...

  9. 【java】Date与String之间的转换及Calendar类:java.text.SimpleDateFormat、public Date parse(String source) throws ParseException和public final String format(Date date)

    package 日期日历类; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util. ...

随机推荐

  1. Resize CentOS Linux hard drive partition (centos 6.3 调整LVS磁盘大小)

    查看当前磁盘信息: [root@localhost ~]# df -h 文件系统          容量  已用  可用 已用%% 挂载点/dev/mapper/VolGroup-lv_root    ...

  2. java 集成友盟推送

    原文:https://blog.csdn.net/Athena072213/article/details/83414743 最近应公司业务需求需要完善友盟推送,认真看了官方文档后其实很简单,只需要细 ...

  3. python list [:1]

    python 切片slice 1.补充: A = np.ones([, , ]) B = np.ones([, ]) C = A*B[:, None, :] C.shape = 2,1,4 https ...

  4. Mysql 密码相关

    MySQL5.6.6版本之后增加了密码强度验证插件validate_password,相关参数设置的较为严格 一.密码复杂度 1.密码复杂度配置文件:/etc/my.cnf  (CentOS 7下) ...

  5. 1009 数字1的数量 数位dp

    1级算法题就这样了,前途渺茫啊... 更新一下博客,我刚刚想套用数位dp的模板,发现用那个模板也是可以做到,而且比第二种方法简单很多 第一种方法:我现在用dp[pos][now]来表示第pos位数字为 ...

  6. 分布式处理框架MapReduce的深入简出

    1).MapReduce的概述 2).MapReduce 编程模型 3).MapReduce架构 4).MapReduce编程 Google MapReduce论文,论文发表于2004年 Hadoop ...

  7. 微信小程序开发——开发者工具无法输入中文的处理

    问题模块 框架类型 问题类型 操作系统 工具版本 开发者工具 小程序 Bug Windows v.02.1810290 异常描述: 无法输入中文,偶现,但是概率有点高,重启,重装,更新版本等等都未解决 ...

  8. 【centos】centos安装g++

    gcc在Centos下的安装:使用的是以下语句:yum install gcc 以为安装g++,类似的应该使用:yum install g++ 可是提示:command is not found 查询 ...

  9. 【Linux 网络编程】TCP网络编程中connect()、listen()和accept()三者之间的关系

    基于 TCP 的网络编程开发分为服务器端和客户端两部分,常见的核心步骤和流程如下: connect()函数:对于客户端的 connect() 函数,该函数的功能为客户端主动连接服务器,建立连接是通过三 ...

  10. jsp页面\n换行替换

    1,js替换 var text= $(this).text(); var reg = new RegExp("\\n","g");//g,表示全部替换. tex ...