이 혼란스러운 C# 코드가 도움이 될 수 있습니다. 단항 연산자는 산술 연산에서 최대 우선 순위를 가지므로 우선 순위가 더 높습니다. 단항 연산자를 식별하기위한 각 연산자 토큰 후에 true로 설정되고 피연산자 뒤에 false로 설정된 부울 변수 unary를 취했습니다. PFE에서 단항 연산자와 이진 연산자를 구별 할 수 있도록 단항 플러스 및 마이너스 연산자에 대해 다른 표기법을 사용해야합니다. 여기 '#'및 '~'는 PFE (후치 표현식)의 단항 플러스 및 단항 빼기를 나타내는 데 사용됩니다.
이 approch를 사용하여 1 + -1,1 + (- 1), 1 --- 1,1 + - 1과 같은 모든 사례를 처리 할 수 있습니다.
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DSA
{
class Calculator
{
string PFE;
public Calculator()
{
Console.WriteLine("Intializing Calculator");
}
public double Calculate(string expression)
{
ConvertToPost(expression);
return CalculatePOST();
}
public void ConvertToPost(string expression)
{
expression = "(" + expression + ")";
var temp = new DSA.Stack<char>();
string ch = string.Empty;
bool unary = true;
char a;
foreach (var b in expression)
{
a = b;
if (!a.IsOperator()) {
ch += a.ToString();
unary = false;
}
else
{
if (ch!=string.Empty)
PFE += ch+",";
ch = string.Empty;
if(a!='(' && a!=')')
{
if (unary == true)
{
if (a == '-') a = '~'; else if (a == '+') a = '#'; else throw new InvalidOperationException("invalid input string");
}
try
{
if (a.Precedence() <= temp.Peek().Precedence())
{
PFE += temp.Pop().ToString() + ",";
}
}
catch(InvalidOperationException e)
{
}
temp.Push(a);
unary = true;
}
if (a == '(') { temp.Push(a);}
if(a==')')
{
for(char t=temp.Pop();t!='(';t=temp.Pop())
{
PFE += t.ToString() + ",";
}
}
}
}
}
public double CalculatePOST()
{
var eval = new Stack<double>();
string ch = string.Empty;
bool skip = false;
foreach(char c in PFE)
{
if(!c.IsOperator())
{
if (c == ',')
{
if (skip == true)
{
skip = false;
continue;
}
eval.Push(Double.Parse(ch));
ch = string.Empty;
}
else ch += c;
}
else
{
if (c == '~')
{
var op1 = eval.Pop();
eval.Push(-op1);
}
else if (c == '#') ;
else
{
var op2 = eval.Pop();
var op1 = eval.Pop();
eval.Push(Calc(op1, op2, c));
}
skip = true;
}
}
return eval.Pop();
}
private double Calc(double op1, double op2, char c)
{
switch(c)
{
case '+':
return op1 + op2;
case '-':
return op1 - op2;
case '*':
return op1 * op2;
case '%':
return op1 % op2;
case '/':
return op1/op2;
case '^':
return float.Parse(Math.Pow(op1,op2).ToString());
default:
throw new InvalidOperationException();
}
}
}
public static class extension
{
public static bool IsOperator(this char a)
{
char[] op = {'+','-','/','*','(',')','^','!','%','~','#'};
return op.Contains(a);
}
public static int Precedence(this char a)
{
if (a == '~' || a== '#')
return 1;
if (a == '^')
return 0;
if (a == '*' || a == '/' || a=='%')
return -1;
if (a == '+' || a == '-')
return -2;
return -3;
}
}
}
@ 자프 쟌 (Jaapjan) : 귀하의 문제가 무엇인지 분명하지 않습니다. 중위 식을 구문 분석합니까? 표현식 트리를 RPN으로 변환하고 있습니까? –
당신은 마이너스 부호를 놓치고, 그것은'1 + 2 ++ 3-4 -' – Andrei