满足正负浮点数运算
public string Compute(string infixExp)
{//1 + 3 * 2 - 6 / 2 1 3 2 *+ 6 2/-
infixExp = infixExp.Replace(" ", "").Replace("=", ""); //过滤空格和等于号
List<string> postfixExp = GetPostfixExp(infixExp);
Stack<string> stack = new Stack<string>();
for (int i = 0; i < postfixExp.Count; i++)
{
if (postfixExp[i] != "+" && postfixExp[i] != "-" && postfixExp[i] != "*" && postfixExp[i] != "/")
{
stack.Push(postfixExp[i]);
}
else
{
double secondNumber = double.Parse(stack.Pop());
double firstNumber = double.Parse(stack.Pop());
double tmpResult = 0;
switch (postfixExp[i])
{
case "+":
tmpResult = firstNumber + secondNumber;
break;
case "-":
tmpResult = firstNumber - secondNumber;
break;
case "*":
tmpResult = firstNumber * secondNumber;
break;
case "/":
tmpResult = firstNumber / secondNumber;
break;
}
stack.Push(tmpResult.ToString());
}
}
return stack.Pop();
}
/// <summary>
/// 先将中缀表达式转为后缀表达式 1+(2-3)*4+10/5 1 2 3 - 4 * + 10 5 / +
/// </summary>
/// <param name="mathExp"></param>
/// <returns></returns>
private List<string> GetPostfixExp(string infixExp)
{
//初始化一个栈存放运算符
Stack<char> stack = new Stack<char>();
//存放后缀表达式字符串
List<string> list = new List<string>();
bool positive = true; //标记正负性
for (int i = 0; i < infixExp.Length; i++)
{
if (infixExp[i] >= '0' && infixExp[i] <= '9')
{
string tmp;
if (!positive)
{
tmp = "-" + infixExp[i];
positive = true;
}
else
{
tmp = "" + infixExp[i];
}
while (i < infixExp.Length - 1 && ((infixExp[i + 1] >= '0' && infixExp[i + 1] <= '9') || infixExp[i + 1] == '.'))
{
tmp += infixExp[i + 1];
i++;
}
list.Add(tmp);
}
else
{
switch (infixExp[i])
{
case '+':
case '-':
if (infixExp[i] == '-')
{
if (i == 0 || infixExp[i - 1] == '(') //-30.0*5或 30*(-4)合法 30*-4不合法
{
positive = false;
break;
}
}
if (stack.Count == 0 || stack.Peek() == '(')
{
stack.Push(infixExp[i]);
}
else
{
while (stack.Count > 0 && stack.Peek() != '(')
{
list.Add(stack.Pop().ToString());
}
stack.Push(infixExp[i]);
}
break;
case '*':
case '/':
while (true)
{
if (stack.Count > 0 && (stack.Peek() == '*' || stack.Peek() == '/'))
{
list.Add(stack.Pop().ToString());
}
else
{
stack.Push(infixExp[i]);
break;
}
}
break;
case '(':
stack.Push(infixExp[i]);
break;
case ')':
while (true)
{
if (stack.Peek() == '(')
{
stack.Pop();
break;
}
else
{
list.Add(stack.Pop().ToString());
}
}
break;
default:
break;
}
}
}
//将栈中剩下的元素依次弹出并加入到list
while (stack.Count > 0)
{
list.Add(stack.Pop().ToString());
}
return list; ;
}
本文介绍了一种通过转换中缀表达式为后缀表达式来实现正负浮点数的混合运算的方法,并提供了详细的代码实现步骤。
840

被折叠的 条评论
为什么被折叠?



