ellapt

T11.7.ArithmExpression

Jan 25th, 2013
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class Rpn
  5. {
  6. public static void Main()
  7. {
  8. Console.WriteLine("Write a program that calculates the value of given arithmetical expression\n");
  9. Console.WriteLine("Please, input the expression in reverse polish notation (Exit with Ctrl/C) :");
  10.  
  11. char[] delimit = new char[] { ' ', '\t' };
  12. for (; ; )
  13. {
  14. string s = Console.ReadLine();
  15. if (s == null) break;
  16.  
  17. // string s = "2.3 5 +";
  18.  
  19. Stack<string> tks = new Stack<string> // the token string: push it into stack
  20. (s.Split(delimit, StringSplitOptions.RemoveEmptyEntries));
  21. if (tks.Count == 0) continue;
  22. try
  23. {
  24. double result = evalRpn(tks);
  25. if (tks.Count != 0) throw new Exception();
  26. Console.WriteLine(result);
  27. }
  28. catch (Exception e) { Console.WriteLine("error"); }
  29. }
  30. }
  31.  
  32. // Evaluate Expression in Reverse Polish Notation
  33. private static double evalRpn(Stack<string> tks)
  34. {
  35. string token = tks.Pop();
  36. double x, y;
  37. if (!Double.TryParse(token, out x))
  38. {
  39. y = evalRpn(tks);
  40. x = evalRpn(tks);
  41. if (token == "+") x += y;
  42. else if (token == "-") x -= y;
  43. else if (token == "*") x *= y;
  44. else if (token == "/") x /= y;
  45. else throw new Exception();
  46. }
  47. return x;
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment