Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace постфикс
- {
- class Program
- {
- static void Main(string[] args)
- {
- // var inFix = "1*2+3-4/5";
- var inFix = "((1+2)*(5+3))/((7-5)*(8-2))";
- // var inFix = "(a*(b+c)+d)/2";
- var postfix = ToPostfix(inFix);
- Console.WriteLine(postfix);
- var solving = SolvePostfix(postfix);
- Console.WriteLine(solving);
- }
- public static double SolvePostfix(string postFix)
- {
- var stackNumbers = new Stack<double>();
- foreach (var ch in postFix)
- if (Char.IsDigit(ch)) stackNumbers.Push(ch-48);
- else if (IsOperation(ch))
- stackNumbers.Push(OperationBetweenTwoOperands(stackNumbers.Pop(), stackNumbers.Pop(), ch));
- return stackNumbers.Pop();
- }
- public static string ToPostfix(string inFix)
- {
- var postFix = string.Empty;
- var stackOperations = new Stack<char>();
- foreach (var ch in inFix)
- {
- if (Char.IsLetterOrDigit(ch))
- {
- postFix += ch;
- }
- else if (IsOperation(ch))
- {
- if ((stackOperations.Count == 0) || ch == '(' || stackOperations.Peek() == '(')
- {
- stackOperations.Push(ch);
- }
- else if ((ch != ')') && (GetPriority(ch) > GetPriority(stackOperations.Peek())))
- {
- stackOperations.Push(ch);
- }
- else if ((ch != ')') && (GetPriority(ch) <= GetPriority(stackOperations.Peek())))
- {
- while ((stackOperations.Count != 0) && ((stackOperations.Peek() != '(') || (GetPriority(stackOperations.Peek()) >= GetPriority(ch))))
- postFix += stackOperations.Pop();
- stackOperations.Push(ch);
- }
- else if (ch == ')')
- {
- while (stackOperations.Peek() != '(') postFix += stackOperations.Pop();
- stackOperations.Pop();
- }
- }
- }
- while (stackOperations.Count != 0) postFix += stackOperations.Pop();
- return postFix;
- }
- public static double OperationBetweenTwoOperands(double left,double right,char operation)
- {
- if (!IsOperation(operation)) throw new InvalidOperationException("Это не операция");
- switch(operation)
- {
- case '+' : return right + left;
- case '-' : return right - left;
- case '*' : return right * left;
- case '/' : return right / left;
- default : return 0;
- }
- }
- public static bool IsOperation(char x) =>
- (x == '(' || x == '+' || x == '-' || x == '*' || x == '/' || x == ')');
- public static int GetPriority(char operation)
- {
- switch (operation)
- {
- case '(': return 0;
- case '+': return 1;
- case '-': return 1;
- case '*': return 2;
- case '/': return 2;
- }
- return -1;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement