运行:

(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. Module build failed: Error: Cannot find module 'url-loader' 的坑

    本文地址:http://www.cnblogs.com/jying/p/8280956.html 开发环境:react.webpack.es5 引用图片报错:Module build failed: ...

  2. Python基础学习Day3 数据类型的转换、int、str、bool、字符串的常用方法、for循环

    一.数据类型的转换 常用的是:int 转str.str转int.int转bool 时   非零即为 True . # 数据类型之间转换 ***** # int <--> str str(i ...

  3. JVM G1GC参数配置

    https://www.oracle.com/technetwork/articles/java/g1gc-1984535.html         主要这两个参数需要设置下,ParallelGCTh ...

  4. idea 设置 转自 https://www.cnblogs.com/jajian/p/8136672.html

    前面已经介绍过Settings上中部分,接下来继续剩余的部分 IntelliJ IDEA(四) :Settings(上) IntelliJ IDEA(五) :Settings(中) 0|1一.Buil ...

  5. 四层协议给站点设置独享ip

    四层协议给站点设置独享ip 初始化为四层节点 设置独占ip 设置独享的产品不用预设置分组 增加站点 创建站点后,在分组解析里会自动创建一个以站点名为名称的分组并且会自动分配一个独享的ip在这个分组里( ...

  6. burpsuite的使用(一)

    安装证书: 打开burpsuite,设置好代理.端口8080,但是打开https的网站却因为证书问题无法访问. 这需要我们为浏览器手动安装CA证书, 安装CA证书有两种方式: 1. 在burpsuit ...

  7. 备份u盘kali系统

    把kali系统装在u盘上,会带来极大的便利,只要有网有机就能随时随地hacking,但是u盘体积太小极易丢失,所以需要对其备份以备万一. 一般kali启动U盘分为两个区:启动区和文件存放区.如下图 我 ...

  8. Springmvc配置时间日期转换

    1.局部日期转换 @Controller public class ProductController{ @RequestMapping(value="/test/springmvc.do& ...

  9. Log4j2配置及使用

    Log4j2:一个日志管理工具.Log4j的升级版,需要Java6以上   一.安装log4j2依赖包 1.通过maven的pom.xml直接引入jar: log4j-api和log4j-core & ...

  10. python使用函数作为参数

    在实际使用中,我们有时希望将函数作为参数传递给另一个方法使用. 比如装饰器实际就是函数调用函数   举个例子,我想传递在调用方法之前打印一下时间:   使用函数当做入参 那就可以把方法名A当做入参传递 ...