using System;
using System.Collections.Generic;
using System.Text;
namespace SimpleCalc
{
static class SimpleCalc
{
private static List<string> listFormu;
private static Stack<string> sNumber;
private static Stack<string> sOperat;
static public double CalcResultValue(List<string> li)
{
listFormu = li;
sNumber = new Stack<string>();
sOperat = new Stack<string>();
return Deal();
}
static private double Deal()
{
for(int i=0;i<listFormu.Count;i++)
{
if (isLeftBracket(listFormu[i])) // (
{
sOperat.Push(listFormu[i]);
}
else if (isRightBracket(listFormu[i]) && sOperat.Count>0) // )
{
string strOp = sOperat.Pop();
if (isOperat(strOp))
{
string strB = sNumber.Pop();
string strA = sNumber.Pop();
sNumber.Push(unaryCalc(Convert.ToDouble(strA), Convert.ToDouble(strB), strOp).ToString());
i--;
}
else//肯定是leftBracket
{
}
}
else if (isOperat(listFormu[i]))//操作符
{
if (isNeedPopOperat(listFormu[i]))//需要pop操作符
{
string strB = sNumber.Pop();
string strA = sNumber.Pop();
sNumber.Push(unaryCalc(Convert.ToDouble(strA), Convert.ToDouble(strB), sOperat.Pop()).ToString());
i--;
}
else
{
sOperat.Push(listFormu[i]);
}
}
else//数字
{
sNumber.Push(listFormu[i]);
}
}
while (sOperat.Count > 0)
{
string strOp = sOperat.Pop();
string strB = sNumber.Pop();
string strA = sNumber.Pop();
sNumber.Push(unaryCalc(Convert.ToDouble(strA), Convert.ToDouble(strB), strOp).ToString());
}
return Convert.ToDouble(sNumber.Pop());
}
private static bool isNeedPopOperat(string p)
{
if (sOperat.Count == 0)
return false;
if (p == "+" || p=="-")
{
if (isOperat(sOperat.Peek()))
return true;
}
else if (p == "*" || p=="/")
{
if (sOperat.Peek()== "*" || sOperat.Peek()=="/")
return true;
}
return false;
}
private static bool isOperat(string p)
{
if (p == "+" || p == "-" || p == "*" || p == "/")
return true;
return false;
}
private static bool isLeftBracket(string p)
{
return p == "(";
}
private static bool isRightBracket(string p)
{
return p == ")";
}
private static double unaryCalc(double a, double b, string strOp)
{
switch (strOp)
{
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
default:
return a;
}
}
}
class Program
{
static void Main(string[] args)
{
List<string> l = new List<string>();
l.Add("26");
l.Add("+");
l.Add("(");
l.Add("1");
l.Add("/");
l.Add("16");
l.Add("/");
l.Add("16");
l.Add(")");
double r = SimpleCalc.CalcResultValue(l);
Console.WriteLine(r);
}
}
}