计算器类(C++&JAVA——表达式转换、运算、模板公式)
运行:
(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——表达式转换、运算、模板公式)的更多相关文章
- java.util.Date日期类通过java语句转换成Sql(这里测试用的是oracle)语句可直接插入(如:insert into)的日期类型
public void add(Emp emp) throws Exception{ QueryRunner runner = new QueryRunner(JdbcUtil.getDataSour ...
- java的大数运算模板
import java.math.BigInteger; import java.util.Scanner; public class Main { public static void main(S ...
- Java初学者作业——定义一个计算器类, 实现计算器类中加、 减、 乘、 除的运算方法, 每个方法能够接收2个参数。
返回本章节 返回作业目录 需求说明: 定义一个计算器类, 实现计算器类中加. 减. 乘. 除的运算方法, 每个方法能够接收2个参数. 实现思路: 定义计算器类. 定义计算器类中加.减.乘.除的方法. ...
- C++做四则运算的MFC计算器(二)栈转换和计算后缀表达式
上篇写了MFC界面搭建,这篇就写实现计算.涉及到数据结构,对新手很不友好. 虽然是MFC程序,但是能灵活地分离后台代码,自行构建控制台程序. 上篇文章链接:C++做四则运算的MFC计算器(一)MFC界 ...
- 利用JAXB实现java实体类和xml互相转换
1.应用场景 在使用WebService实现数据上传下载,数据查询时,可以利用JAXB实现java实体类和xml互相转换 2.Demo 2.1 student.java 实体类,包含list(set同 ...
- Java中int类型和tyte[]之间转换及byte[]合并
JAVA基于位移的 int类型和tyte[]之间转换 [java] view plaincopy /** * 基于位移的int转化成byte[] * @param int number * @retu ...
- 我的Android进阶之旅------>Java文件大小转换工具类 (B,KB,MB,GB,TB,PB之间的大小转换)
Java文件大小转换工具类 (B,KB,MB,GB,TB,PB之间的大小转换) 有时候要做出如下所示的展示文件大小的效果时候,需要对文件大小进行转换,然后再进行相关的代码逻辑编写. 下面是一个Java ...
- 用MyEclipse将java文件转换成UML类图
用MyEclipse将java文件转换成UML类图 参考: 用MyEclipse将java文件转换成UML类图 - 君临天下的博客 - CSDN博客 http://blog.csdn.net/dan ...
- 【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. ...
随机推荐
- Eclipse绿豆沙护眼
Window-->Preferences-->Editors——>Text Editors —— Background color 背景颜色向你推荐:色调:85.饱和度:123.亮度 ...
- Spark之机器学习(Python版)(一)——聚类
https://www.cnblogs.com/charlotte77/p/5437611.html
- 安装opencv3.x卡在ICV: Downloading ippicv_linux_20151201.tgz...
参考:http://blog.csdn.net/bobsweetie/article/details/52502741 可以自己下载: ICV: Downloading ippicv_linux_20 ...
- SpringBoot @Async注解失效分析
有时候在使用的过程中@Async注解会失效(原因和@Transactional注解有时候会失效的原因一样). 下面定义一个Service: 两个异步执行的方法test03()和test02()用来模拟 ...
- spring boot springmvc视图
pring boot 在springmvc的视图解析器方面就默认集成了ContentNegotiatingViewResolver和BeanNameViewResolver,在视图引擎上就已经集成自动 ...
- sql语句中的不等于 <>
建议最好使用 <> 表示不等于 原因:!=在sql2000不表示不等于
- centos静态绑定IP地址
Centos7 /etc/sysconfig/network-scripts/ifcfg-ens33
- Lattice Constants and Crystal Structures of some Semiconductors
Lattice Constants and Crystal Structures of some Semiconductors and Other Materials Element or Compo ...
- CentOS SELinux服务关闭与开启
查看SElinux是否开启 查看是否开启SELinux,如果是未开启则是diabled,enforcing(enforce的分词,正在执行的意思),表明开启 #getenforce 临时关闭S ...
- 81. Search in Rotated Sorted Array II (Array; Divide-and-Conquer)
Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed? Would this ...