Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Data;
- namespace calcu
- {
- class Program
- {
- // Function to transform an infix expression to its postfix form.
- static string InfixPostfix(string infix)
- {
- string postfix = "";
- Stack<char> opers = new Stack<char>();
- if(infix[0] == '-')
- {
- infix = "0" + infix;
- }
- for (int i = 0; i < infix.Length; i++)
- {
- if (infix[i] == ' ') { continue; }
- if (!"+*/-()".Contains(infix[i]))
- {
- postfix += infix[i];
- }
- else if ("+*/-".Contains(infix[i]))
- {
- postfix += ' ';
- while ((opers.Count != 0) && opers.Peek() != '(' && IsFirstStronger(opers.Peek(), infix[i]))
- {
- postfix += opers.Pop();
- postfix += ' ';
- }
- opers.Push(infix[i]);
- }
- else if (infix[i] == '(')
- {
- opers.Push('(');
- }
- else if(infix[i] == ')')
- {
- while(opers.Count()!= 0 && opers.Peek() != '(')
- {
- postfix += ' ';
- postfix += opers.Pop();
- }
- opers.Pop();
- }
- }
- while (opers.Count != 0)
- {
- postfix += ' ';
- postfix += opers.Pop();
- }
- return postfix;
- }
- // Function to compare the precedence of two operators giving as input
- // and returns true if the first has higher order than the second.
- static bool IsFirstStronger(char nibber1, char nibber2)
- {
- Dictionary<char, int> d = new Dictionary<char, int>()
- {
- {'*', 2},
- {'/', 2},
- {'+', 1},
- {'-', 1}
- };
- if (d[nibber1] == d[nibber2])
- {
- return true;
- }
- return d[nibber1] > d[nibber2];
- }
- // Function to evaluate a postfix expression.
- static float EvaluatePostfix(string postfix)
- {
- float result = 0f;
- List<string> expression = new List<string>();
- expression = postfix.Split(' ').ToList();
- string temp = "";
- Stack<string> oprand = new Stack<string>();
- foreach (string ele in expression)
- {
- if (!"+-/*".Contains(ele))
- {
- oprand.Push(ele);
- }
- else if ("+-/*".Contains(ele))
- {
- oprand.Push(Compute(oprand.Pop(), oprand.Pop(), ele[0]).ToString());
- }
- }
- return float.Parse(oprand.Pop());
- }
- static float Compute(string num2, string num1, char oper)
- {
- float intarino1 = float.Parse(num1);
- float intarino2 = float.Parse(num2);
- switch (oper)
- {
- case '+':
- return intarino1 + intarino2;
- case '-':
- return intarino1 - intarino2;
- case '*':
- return intarino1 * intarino2;
- case '/':
- return intarino1 / intarino2;
- default:
- return 5;
- }
- }
- static void Main()
- {
- string input;
- while (true)
- {
- Console.WriteLine("mathematical expression (type x to exit):");
- input = Console.ReadLine();
- Console.WriteLine($"postfix notation : {InfixPostfix(input)}");
- Console.WriteLine($"result = {EvaluatePostfix(InfixPostfix(input))}");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement