Reputation: 347
I have an assignment to create a postfix notation from the infix. I got the code working properly and i have a string of the postfix notation, however I'm not sure how to get the answer from it. Is there a .NET method I can call? I tried Googling the problem and can only find how to change it to post fix.
Any help is much appreciated.
Update I needed to find the answer to an expression like: 12+3-4+5-
I was hoping to find an easier way to do this but I did not so i wrote my own method to. I will post it in 8 hours when i am allowed to.
Upvotes: 0
Views: 8892
Reputation: 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace pof
{
class eva
{
public string po;
public string answer;
Stack i = new Stack();
public void e()
{
int a, b, ans;
for (int j = 0; j < po.Length; j++)
{
String c = po.Substring(j, 1);
if (c.Equals ("*"))
{
String sa = (String)i.Pop();
String sb = (String)i.Pop();
a = Convert.ToInt32(sb);
b = Convert.ToInt32(sa);
ans = a * b;
i.Push(ans.ToString());
}
else if (c.Equals("/"))
{
String sa = (String)i.Pop();
String sb = (String)i.Pop();
a = Convert.ToInt32(sb);
b = Convert.ToInt32(sa);
ans = a / b;
i.Push(ans.ToString());
}
else if (c.Equals("+"))
{
String sa = (String)i.Pop();
String sb = (String)i.Pop();
a = Convert.ToInt32(sb);
b = Convert.ToInt32(sa);
ans = a + b;
i.Push(ans.ToString());
}
else if (c.Equals("-"))
{
String sa = (String)i.Pop();
String sb = (String)i.Pop();
a = Convert.ToInt32(sb);
b = Convert.ToInt32(sa);
ans = a - b;
i.Push(ans.ToString());
}
else
{
i.Push(po.Substring(j, 1));
}
}
answer=(String)i.Pop();
}
}
class Program
{
static void Main(string[] args)
{
eva e1 = new eva();
Console.WriteLine("enter any postfix expression");
e1.po = Console.ReadLine();
e1.e();
Console.WriteLine("\n\t\tpostfix evaluation: " + e1.answer);
Console.ReadKey();
}
}
}
Upvotes: 0
Reputation: 347
Postfix is the expression in a string like "10 9 + 7 % 3 - "
postfix = postfix.Trim();
string[] ans = postfix.Split(' ');
Stack<int> eval = new Stack<int>();
for (int x = 0; x < ans.Length; x++)
{
if ("*+%/-".Contains(ans[x]))
{
int temp1;
int temp2;
switch (ans[x])
{
case ("*"):
eval.Push(eval.Pop() * eval.Pop());
break;
case "-":
temp1 = eval.Pop();
temp2 = eval.Pop();
eval.Push(temp2 - temp1);
break;
case "%":
temp1 = eval.Pop();
temp2 = eval.Pop();
eval.Push(temp2 % temp1);
break;
case "+":
eval.Push(eval.Pop() + eval.Pop());
break;
case "/":
temp1 = eval.Pop();
temp2 = eval.Pop();
eval.Push(temp2 / temp1);
break;
}
}
else
eval.Push(Convert.ToInt32(ans[x]));
}
//Cut the code off too soon. after the for statement is done executing the answer will be int answer = eval.Pop();
Upvotes: 3