Time Limit: 2000/1000 MS (java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 19484 Accepted Submission(s): 6860
讀入一個只包含 +, -, *, / 的非負整數計算表達式,計算該表達式的值。
測試輸入包含若干測試用例,每個測試用例占一行,每行不超過200個字符,整數和運算符之間用一個空格分隔。沒有非法表達式。當一行中只有0時輸入結束,相應的結果不要輸出。
對每個測試用例輸出1行,即該表達式的值,精確到小數點后2位。
1 + 2 4 + 2 * 5 - 7 / 11 0
3.00 13.36
題解:棧原理。先處理乘除,再處理加減。
//Java代碼import java.util.Scanner;public class Main { public static void main(String[] args) { double[] num = new double[201]; char[] sign = new char[201]; Scanner in = new Scanner(System.in); while(in.hasNextLine()){ String str = in.nextLine(); if(str.equals("0")) break; String[]strs = str.split(" "); int j = 0; int k = 0; //處理乘除 for(int i=0;i<strs.length;i++){ if(strs[i].equals("*") || strs[i].equals("/") || strs[i].equals("+") || strs[i].equals("-")){ switch(strs[i]){ case "+": sign[k++] = '+';break; case "-": sign[k++] = '-';break; case "*": num[j-1] = num[j-1]*Integer.valueOf(strs[i+1]); i++; break; case "/": num[j-1] = num[j-1]/Integer.valueOf(strs[i+1]); i++; break; } }else{ num[j++] = Integer.valueOf(strs[i]); } } int l = 0; double res = 0; //處理加減 for(int i=0;i<j;i++){ if(i==0){ res = num[i]; continue; } switch(sign[l]){ case '+': res += num[i]; l++; break; case '-': res -= num[i]; l++; break; } } System.out.println(String.format("%.2f", res)); //初始化數組 for(int i=0;i<num.length;i++){ num[i] = 0; sign[i] = ' '; } } }}新聞熱點
疑難解答