四则运算算法
为了忘却的纪念;
一个表达式 1+2*3可以写成: a+b*1+2*3,其中a=0,b=1; 查看每一个数字后面的符号, 如果是+号,计算出a, 把b设置为1; 如果是*号,a保留不变,计算b; 最后结果 就是 a+b*temp;
package com.stono;
/**
* @author stono
*/
public class Calc01 {
public static void main(String[] args) {
String str = "1+6/2";
char[] chars = str.toCharArray();
double a = 0, b = 1, temp = 0;
boolean div = false;
for (char aChar : chars) {
if (Character.isDigit(aChar)) {
temp = Double.parseDouble(String.valueOf(aChar));
if(div){
temp = 1/temp;
}
} else {
div = false;
String calc = String.valueOf(aChar);
if ("+".equals(calc)) {
a = a + b * temp;
b = 1;
}
if ("-".equals(calc)) {
a = a + b * temp;
b = -1;
}
if ("*".equals(calc)) {
b = b * temp;
}
if("/".equals(calc)){
b = b*temp;
div = true;
}
}
}
System.out.println(a + b * temp);
}
}
来源:https://www.cnblogs.com/stono/p/12298602.html