表达式求值
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
ACM队的mdd想做一个计算器,但是,他要做的不仅仅是一计算一个A+B的计算器,他想实现随便输入一个表达式都能求出它的值的计算器,现在请你帮助他来实现这个计算器吧。
比如输入:“1+2/4=”,程序就输出1.50(结果保留两位小数)-
输入
-
第一行输入一个整数n,共有n组测试数据(n<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。
数据保证除数不会为0
输出
- 每组都输出该组运算式的运算结果,输出结果保留两位小数。 样例输入
-
2 1.000+2/4= ((1+2)*5+1)/4=
样例输出
-
1.50 4.00
-
第一行输入一个整数n,共有n组测试数据(n<10)。
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
String cc = scanner.nextLine();
while (number-- != 0) {
String string = scanner.nextLine();
Stack<Character> stack = new Stack<Character>();
StringBuilder suffix = new StringBuilder("");
for (int i = 0; i < string.length(); i++) {
char temp = string.charAt(i);
if ((temp >= '0' && temp <= '9') || temp == '.') {
suffix.append(temp);
} else {
if (temp == '+' || temp == '-') {
suffix.append(" ");
if (stack.isEmpty()) {
stack.push(temp);
} else {
char top = stack.peek();
if (top == '(') {
stack.push(temp);
} else {
while (!stack.isEmpty() && stack.peek() != '(') {
suffix.append(stack.pop() + " ");
}
stack.push(temp);
}
}
} else if (temp == '*' || temp == '/') {
suffix.append(" ");
if (stack.isEmpty()) {
stack.push(temp);
} else {
char top = stack.peek();
if (top == '+' || top == '-' || top == '(') {
stack.push(temp);
} else if (top == '*' || top == '/') {
suffix.append(stack.pop() + " ");
stack.push(temp);
}
}
} else if (temp == '(') {
stack.push(temp);
} else if (temp == ')') {
char top = stack.pop();
while (top != '(') {
suffix.append(" " + top);
top = stack.pop();
}
} else if (temp == '=') {
while (!stack.isEmpty()) {
suffix.append(" " + stack.pop());
}
suffix.append(" " + "=");
}
}
}
Stack<Double> result = new Stack<Double>();
String arr[] = suffix.toString().split(" ");
for (int j = 0; j < arr.length; j++) {
char temp = arr[j].charAt(0);
double value = 0;
if (temp >= '0' && temp <= '9') {
value = Double.valueOf(arr[j]);
result.push(value);
} else if (temp == '+') {
double one = result.pop();
double two = result.pop();
double three = one + two;
result.push(three);
} else if (temp == '-') {
double one = result.pop();
double two = result.pop();
double three = two - one;
result.push(three);
} else if (temp == '*') {
double one = result.pop();
double two = result.pop();
double three = one * two;
result.push(three);
} else if (temp == '/') {
double one = result.pop();
double two = result.pop();
double three = two / one;
result.push(three);
} else if (temp == '=') {
System.out.printf("%.2f\n", result.pop());
}
}
}
}
}