float str2num(char[] str) { … } char[] num2str(float num) { … } float calc(char[] exp) { … }Java:
float str2num(String str) { … } String num2str(float num) { … } float calc(String exp) { … }
float str2num(char[] str) { … } char[] num2str(float num) { … } float calc(char[] exp) { … }Java:
float str2num(String str) { … } String num2str(float num) { … } float calc(String exp) { … }
float expr(char* s, int& pos); float term(char* s, int& pos); float factor(char* s, int& pos); float number(char* s, int& pos); float expr(char* s, int& pos) { float v = term(s, pos); while (s[pos] == '+' || s[pos] == '-') { if (s[pos++] == '+') v += term(s, pos); else v -= term(s, pos); } return v; } float term(char* s, int& pos) { float v = factor(s, pos); while (s[pos] == '*' || s[pos] == '/') { if (s[pos++] == '*') v *= factor(s, pos); else v /= factor(s, pos); } return v; } float factor(char* s, int& pos) { if (s[pos] == '(') { pos++; float v = expr(s, pos); pos++; return v; } else { return number(s, pos); } } float number(char* s, int& pos) { int n = 0; while (s[pos] >= '0' && s[pos] <= '9') n = n * 10 + s[pos++] - '0'; return (float)n; } float calc(char[] exp) { int pos = 0; return expr(exp, pos); }
//中缀表达式转后缀表达式 //一个符号栈,一个数栈 #include <bits/stdc++.h> using namespace std; #define type float float str2num(char p[]); int signPriority(char op); type cal2(type a,type b,char op); void calModel(stack<type>& numberStack,char op); float calc(char str[]); float str2num(char p[]){ type number; sscanf(p,"%lf",&number); return number; } int signPriority(char op){ if(op=='(') return 0; if((op=='+')||(op=='-')) return 1; if((op=='*')||(op=='/')) return 2; } type cal2(type a,type b,char op){ switch(op){ case '+': return a+b; case '-': return a-b; case '*': return a*b; case '/': return a/b; } } void calModel(stack<type>& numberStack,char op){ type post = numberStack.top(); numberStack.pop(); type pre = numberStack.top(); numberStack.pop(); numberStack.push(cal2(pre,post,op)); } float calc(char str[]){ stack<char> signStack; stack<type> numberStack; int end = strlen(str); for(int i=0;i<end;){ //跳过"" while(i<end&&str[i]==' ') i++; //碰到符号 if(!isdigit(str[i])) { char c = str[i++]; if(c=='(') signStack.push(c); else if(c==')'){ while((!signStack.empty())&&signStack.top()!='('){ calModel(numberStack,signStack.top()); signStack.pop(); } //删去'(' signStack.pop(); }else{ int curPriority = signPriority(c); while((!signStack.empty())&&(curPriority<=signPriority(signStack.top()))){ calModel(numberStack,signStack.top()); signStack.pop(); } signStack.push(c); } } else { //数字是连续的 string tmp = ""; while (i < end && isdigit(str[i])) tmp += str[i++]; char* p = (char*)tmp.data(); numberStack.push(str2num(p)); } } while(!signStack.empty()){ calModel(numberStack,signStack.top()); signStack.pop(); } return numberStack.top(); }
private static void calc(String exp) { Stack<Integer> stackNum = new Stack<>(); Stack<Character> operate = new Stack<>(); for (int i = 0; i < exp.length(); i++) { char c = exp.charAt(i); int num = c - '0'; if (num >= 0 && num <= 9) { stackNum.push(num); } else { switch (c) { case '+': case '-': if (operate.size() > 0) { Character peek = operate.peek(); while (operate.size() > 0 && peek == '*' || peek == '/') { peek = operate.pop(); switch (peek) { case '*': stackNum.push((stackNum.pop() * stackNum.pop())); break; case '/': int num2 = stackNum.pop(); if (num2 == 0) { System.out.println("除数不得为0!"); return; } stackNum.push(stackNum.pop() / num2); break; } } } operate.push(c); break; case '*': case '/': case '(': operate.push(c); break; case ')': char pop; while (operate.size() > 0 && (pop = operate.pop()) != '(') { calcRun(stackNum, pop); } break; } } } while (operate.size() > 0 && stackNum.size() > 0) { calcRun(stackNum, operate.pop()); } System.out.println(stackNum.pop()); } private static void calcRun(Stack<Integer> stackNum, char pop) { Integer res = null; switch (pop) { case '+': res = stackNum.pop() + stackNum.pop(); break; case '-': res = -(stackNum.pop() - stackNum.pop()); break; case '*': res = stackNum.pop() * stackNum.pop(); break; case '/': int t = stackNum.pop(); if (t == 0) { System.out.println("除数不得为0!"); return; } res = stackNum.pop() / t; break; } if (res != null) { stackNum.push(res); } }
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import
java.util.List;
/**
* 实现字符串输入之后的四则运算
* @author Administrator
*
*/
public class Math {
public static void
main(String[] args) throws IOException {
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
resultShow(br);
// System.out.println(9-7*8);
// System.out.println(getResult("9-7*8"));
}
public static void resultShow(BufferedReader br) throws
IOException{
System.out.print("请输入计算式:");
//开始接受用户指令
String str = br.readLine();
try {
double result = getResult(str);
if((double)0 == result -
(int)result){
System.out.println("计算后得出的结果为:"+(int)result);
}else{
System.out.println("计算后得出的结果为:"+result);
}
} catch (Exception e) {
// TODO Auto-generated catch
block
e.printStackTrace();
System.out.println("您输入的公式不正确!请重新输入");
resultShow(br);
}
}
/**
*
首先将计算式转换为Object数组,数字转为int,符号为String
* @param expr
*
@return
*/
public static double getResult(String expr){
//转换char数组
char[] cs = expr.toCharArray();
//转换后存放公式内容的容器
List<Object>intData = new
ArrayList<Object>();
//这个对象用来存放一串连续数字的char字符
List<Character> temp = new ArrayList<Character>();
for (int i = 0; i < cs.length; i++) {
if((int)cs[i] - 48
< 0 && (int)cs[i]-48 != -2){//判断是否为符号
intData.add(cs[i]+"");
temp.clear();
}
//判断如果是数字且当前是最后一位或者下一个char字符是符号,结束连续数字判断,转换连续数字为int,并添加到转换后的容器
else if((int)cs[i] - 48 >= 0 && (i==cs.length-1 ||
((int)cs[i+1] - 48 < 0 && (int)cs[i+1]-48 != -2))){
temp.add(cs[i]);
intData.add(getCharDouble(temp));
}
else{//非以上两种情况,则认为下个char字符也为数字,直接添加到临时变量
temp.add(cs[i]);
}
}
return
getActualResult(intData.toArray());
}
/**
*
拼接连续数字并转换为int
* @param temp
* @return
*/
public
static double getCharDouble(List<Character> temp){
String
s = "";
for (Iterator i = temp.iterator();
i.hasNext();) {
Character character = (Character) i.next();
s += character;
}
return
Double.parseDouble(s);
}
public static double
getActualResult(Object[] cs){
return kuohaoMath(cs);
}
/**
* 带括号计算,使用递归
*/
public static double
kuohaoMath(Object[] cs){
//找到扩号符的索引,正反括号
int[]
indexe敏感词indKuohaoIndex(cs);
if(indexes != null){
Object[] temp = new Object[indexes[1]-indexes[0]-1];
//截获括号里面的内容数组
for (int i = 0; i < temp.length; i++) {
temp[i] = cs[indexes[0]+1+i];
}
//然后开始计算括号里面的值
double result = normalMath(temp);
//计算完成后添加到新容器,并递归继续找括号
List<Object> tempData = new ArrayList<Object>();
for (int i = 0; i < cs.length; i++) {
if(i ==
indexes[0]){
tempData.add(result);
}else
if(i<indexes[0] || i > indexes[1]){
tempData.add(cs[i]);
}
}
return
kuohaoMath(tempData.toArray());
}else{
//如果无括号则直接返回普通计算值
return normalMath(cs);
}
}
/**
* 首先需要找到最里层括号的索引
*/
public static int[]
findKuohaoIndex(Object[] cs){
int[] indexes = null;
for
(int i = 0; i < cs.length; i++) {
//从头开始找,先找最近的反括号
if(cs[i].equals(")")){
indexes = new int[2];
indexes[1] = i;
//然后去找最近的正括号
for (int j = i-1; j
>=0; j--) {
if(cs[j].equals("(")){
indexes[0] = j;
break;
}
}
break;
}
}
return indexes;
}
/**
* 不包括括号运算的,普通运算算法
*/
public static double
normalMath(Object[] cs){
int index = -1;
//先乘法或除法,找到*,/的索引位置
index = findMultiplication(cs);
if(index >= 0){
List<Object> tempData = new
ArrayList<Object>();
//计算符号附近相邻值得结果
double result
= 0;
if(cs[index].equals("*")){
result =
(Double)cs[index-1] * (Double)cs[index+1];
}else{
result = (Double)cs[index-1] / (Double)cs[index+1];
}
//添加到新容器
for (int i = 0; i < cs.length; i++) {
if(i != index - 1 && i != index +1 && i !=
index){
tempData.add(cs[i]);
}else if(i ==
index){
tempData.add(result);
}
}
//继续向下递归
return normalMath(tempData.toArray());
}
//如果没有乘法和除法了,那么开始加减算法,原理与乘法相同
index = findAdd(cs);
if(index >= 0){
List<Object> tempData = new
ArrayList<Object>();
//计算符号附近相邻值得结果
double result
= 0;
if(cs[index].equals("+")){
result =
(Double)cs[index-1] + (Double)cs[index+1];
}else{
result = (Double)cs[index-1] - (Double)cs[index+1];
}
for (int i = 0; i < cs.length; i++) {
if(i != index - 1
&& i != index +1 && i != index){
tempData.add(cs[i]);
}else if(i == index){
tempData.add(result);
}
}
return
normalMath(tempData.toArray());
}
//计算出最终结果时,只有一个值了
return (Double) cs[0];
}
/**
*
查找数组中加减的符号位置
*/
public static int findAdd (Object[]
cs){
for (int i = 0; i < cs.length; i++) {
if(cs[i].equals("+") ||
cs[i].equals("-")){//-5是加号,-3是减号
return i;
}
}
return -1;
}
/**
*
查找数组中乘除的符号位置
*/
public static int findMultiplication
(Object[] cs){
for (int i = 0; i < cs.length; i++) {
if(cs[i].equals("*") || cs[i].equals("/")){
return i;
}
}
return -1;
}
}