من قبلا برای این کار یک کلاس هم طراحی کردم
حالشو ببر
public class Calculator
{
private string[] _operator = {"(","+", "-", "*", "/" , " "};
private int[] _weightOPerator = { 0, 12, 12, 13, 13 ,13};
private string _strString ;
public string strString
{
get { return (_strString); }
set { _strString = value; }
}
public double Calculate()
{
System.Collections.Generic.List<char> Postfix = new System.Collections.Generic.List<char>();
PostfixtoInfix(strString,ref Postfix);
return(Proccess(Postfix));
}
private void PostfixtoInfix(string infix,ref System.Collections.Generic.List<char> Postfix)
{
System.Collections.Stack stack = new System.Collections.Stack();
char op=' ';
for (int i = 0; i < infix.Length; i++)
{
if (infix[i] == '(')
stack.Push('(');
else if (infix[i] == ')')
{
char tmp;
while (stack.Count != 0)
{
tmp = (char)stack.Pop();
if (tmp != '(')
Postfix.Add(tmp);
else
break;
}
}
else if (infix[i] >= '0' && infix[i] <= '9')
Postfix.Add(infix[i]);
else
{
try
{
op = (char)stack.Pop();
stack.Push(op);
}
catch { }
//op >= str
if (!Pred(op, strString[i])==true || stack.Count==0 )
{
//if(op!=' ')
// stack.Push(op);
stack.Push(strString[i]);
}
else
{
op = (char)stack.Pop();
while (Pred(op,strString[i])==true)
{
Postfix.Add(op);
if (stack.Count == 0)
break;
op = (char)stack.Pop();
}
stack.Push(strString[i]);
}
}
}
while (stack.Count!=0)
{
op =(char) stack.Pop();
Postfix.Add(op);
}
}
private bool Pred(char op1,char op2)
{
int p1=0, p2=0;
for (int i = 0; i < _operator.Length; i++)
{
if (op1.ToString()==_operator[i])
{
p1 = i;
}
}
for (int i = 0; i < _operator.Length; i++)
{
if (op2.ToString() == _operator[i])
{
p2 = i;
}
}
if (_weightOPerator[p1] >= _weightOPerator[p2])
return true;
else
return false;
}
private double Proccess(System.Collections.Generic.List<char> Postfix)
{
System.Collections.Generic.Stack<double> stack = new System.Collections.Generic.Stack<double>();
char symbol;
double operand1, operand2,result;
for (int i = 0; i < Postfix.Count; i++)
{
symbol = Postfix[i];
if (symbol >= '0' && symbol <= '9')
{
stack.Push((double)Postfix[i]-48);
}
else
{
operand2 = stack.Pop();
operand1 = stack.Pop();
result = Operate(symbol, operand1, operand2);
stack.Push(result);
}
}
return( stack.Pop());
}
private double Operate(char symbol, double opr1, double opr2)
{
double result=0.0;
switch (symbol.ToString())
{
case "+":
result = opr1 + opr2;
break;
case "-":
result = opr1 - opr2;
break;
case "*":
result = opr1 * opr2;
break;
case "/":
result = opr1 / opr2;
break;
}
return (result);
}
}
فقط کافیه مقدار ورودی و به strString بدی و متد Calculate() رو فراخوانی کن