参考代码:
import java.util.Scanner; import java.util.Stack; //逆波兰表达式 public class Main { public static void main(String[] args) { //输入逆波兰表达式字符串 Scanner sc = new Scanner(System.in); String str = sc.nextLine(); String [] arr = str.split(" "); double result = getResult(arr); System.out.printf("%6f",result); } public static double getResult(String [] arr){ Stack<Double> stack = new Stack<>(); //反向遍历字符串(题目中要求前置表达式) for(int i = arr.length-1;i>=0;i--){ if(arr[i].equals("+") || arr[i].equals("-") || arr[i].equals("*") || arr[i].equals("/")){ double number1 = stack.pop(); double number2 = stack.pop(); switch (arr[i]){ case "+": stack.push(number1 + number2); break; case "-": stack.push(number1 - number2); break; case "*": stack.push(number1 * number2); break; case "/": stack.push(number1 / number2); break; } }else{ stack.push(Double.parseDouble(arr[i])); } } return stack.pop(); } }
0.0分
1 人评分
字符串比较 (C语言代码)答案错误????浏览:641 |
A+B for Input-Output Practice (IV) (C语言代码)浏览:484 |
C语言训练-求s=a+aa+aaa+aaaa+aa...a的值 (C语言代码)浏览:636 |
【计算球体积】 (C语言代码)浏览:1158 |
C语言程序设计教程(第三版)课后习题5.6 (C语言代码)浏览:580 |
DNA (C语言代码)浏览:564 |
用筛法求之N内的素数。 (C语言代码)浏览:711 |
C语言程序设计教程(第三版)课后习题1.6 (C语言代码)浏览:524 |
循环入门练习5 (C语言代码)浏览:908 |
C二级辅导-温度转换 (C语言代码)浏览:802 |