HDU,1237,简略计算器
HDU,1237,简单计算器
Total Submission(s): 11983 Accepted Submission(s): 3901
简单计算器
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 11983 Accepted Submission(s): 3901
Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0
Sample Output
3.00 13.36
Source
浙大计算机研究生复试上机考试-2006年
import java.text.DecimalFormat; import java.util.Scanner; import java.util.Stack; public class T1024 { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s = input.nextLine(); while (s.compareTo("0") != 0) { Stack<Double> num = new Stack<Double>(); // Stack<Character> si = new Stack<Character>(); Scanner cin = new Scanner(s); while (cin.hasNext()) { String s1 = cin.next(); char c = s1.charAt(0); if (c == '+') { // si.push(c); continue; } if (c == '-') { // si.push('+'); double hou = cin.nextDouble(); num.push(-1 * hou); continue; } if (c == '*' || c == '/') { double hou = cin.nextDouble(); double qian = num.pop(); if (c == '/') num.push(qian / hou); if (c == '*') num.push(qian * hou); continue; } num.push(Double.parseDouble(s1)); } double ans = 0; while (!num.empty()) { ans += num.pop(); } /* DecimalFormat f = new DecimalFormat("0.00"); System.out.println(f.format(ans)); */ /* System.out.printf("%.2f", ans); System.out.println(); */ System.out.printf(String.format("%.2f", ans)); System.out.println(); s = input.nextLine(); } } }
刚开始加入的符号的栈,后来才知道,负号可以直接当成下一个数的符号,这样处理就简单多了,但还是错了好几遍,最后发现是不能用DecimalFormat,改成System.out.printf("%.2f", ans);就过了,后来问学长以后来还是用System.out.printf(String.format("%.2f", ans));吧