四则运算中对负数的处理
解决方法:在负数前面进行补0,如 -a-100
-> (0-a)-100
, 之后用逆波兰表达的方法计算即可。
java 测试代码:
public static void main(String[] args) throws Exception{
String[] exps = new String[]{"-a-100", "a-b-1", "a-(b-b)", "(y-0.123)-99.87", "A*(-1)", "(-b)/c", "-0.12*c", "a+-123.333/c","(a+-1)/c","a+(-1.5/c)", "c-(1.2-7.8)", "t-1.7777", "a+ b /3 +(2 + cccc)+(123)", "a+ -b /3 +(-2 + cccc)+(123)"};
for (String exp : exps) {
String newExp = exp.replaceAll("(?<![0-9a-zA-Z\\)])-(\\d+(\\.\\d+)*|\\w+)", "(0-$1)");
System.out.printf("%s -> ", exp);
System.out.println(newExp);
}
}
结果:
-a-100 -> (0-a)-100
a-b-1 -> a-b-1
a-(b-b) -> a-(b-b)
(y-0.123)-99.87 -> (y-0.123)-99.87
A*(-1) -> A*((0-1))
(-b)/c -> ((0-b))/c
-0.12*c -> (0-0.12)*c
a+-123.333/c -> a+(0-123.333)/c
(a+-1)/c -> (a+(0-1))/c
a+(-1.5/c) -> a+((0-1.5)/c)
c-(1.2-7.8) -> c-(1.2-7.8)
t-1.7777 -> t-1.7777
a+ b /3 +(2 + cccc)+(123) -> a+ b /3 +(2 + cccc)+(123)
a+ -b /3 +(-2 + cccc)+(123) -> a+ (0-b) /3 +((0-2) + cccc)+(123)
人生如修仙,岂是一日间。何时登临顶,上善若水前。