计算 数学表达式
- 标量的值 搞个字典《string ,double》
- 更具 操作符号 ,分割字符串
- 更具 优先级把数据 push stack
- 再每次 分别 pop 2个数据,和 一个操作符,一直到全部结束
效果下图如图
部分核心代码如下
/// <summary>
/// 空 stack 返回 true
/// </summary>
/// <returns>空 stack 返回 true</returns>
private bool IsEmpty(Stack st)
{
return st.Count == 0 ? true : false;
}
private double GetValue(string op, double numFir, double numSec)
{
switch (op)
{
case "+":
return numSec + numFir;
case "-":
return numSec - numFir;
case "*":
return numSec * numFir;
case "/":
return numSec / numFir;
default:
return 0;
}
}
public bool GetCompare(string op, double numFir, double numSec)
{
switch (op)
{
case ">":
return numFir > numSec;
case "<":
return numFir < numSec;
default:
throw new NotImplementedException();
}
}
public double Calculate(List<string> ListstrA)
{
double numFir, numSec, ret;
string temp;
Stack myStack = new System.Collections.Stack();
//Stack<string> stacks = new Stack<string>();
foreach (string str in ListstrA)
{
temp = str;
if (IsOperand(temp))// 如果数据,非操作符号 push stack
{
myStack.Push(temp);
}
else //if operate , caculate
{
object obNum1 = myStack.Pop();
numFir = obj2num(obNum1);
object obNum2 = myStack.Pop();
numSec = obj2num(obNum2);
ret = GetValue(temp, numFir, numSec);
myStack.Push(ret);
}
}
return (double)myStack.Pop();
}
public List<string> StringSpit(string StrSource)
{
char[] strarray = StrSource.ToCharArray();
List<string> ListStr = new List<string>();
int start = 0;
int LastOpIndex = 0;
string temp;
for (int i = 0; i < strarray.Length; i++)
{
switch (strarray[i])
{
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
case '>':
case '<':
temp = StrSource.Substring(start, i - start);
if (!string.IsNullOrEmpty(temp)) //数字 部分
{
ListStr.Add(temp.Trim());
}
temp = StrSource.Substring(i, 1);
if (!string.IsNullOrEmpty(temp))// 操作符 部分
{
ListStr.Add(temp);
}
start = i + 1;
LastOpIndex = i;
break;
}
// 会漏掉 最后一个 操作符后面的东西
if (i == strarray.Length - 1)
{
string tempStr = StrSource.Substring(LastOpIndex + 1, strarray.Length - LastOpIndex - 1);
ListStr.Add(tempStr);
}
}
return ListStr;
}