using System;
using System.Text.RegularExpressions;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Stack num = new Stack();
Stack oper = new Stack();
string expression = "12 + 56 + 77";
Calculate(num, oper, expression);
Console.WriteLine(num.Pop());
Console.ReadKey();
}
//IsNumberic isn't built into C# so we must define it
static bool IsNumberic(string input)
{
bool flag = true;
string patten = (@"^\d+$");
Regex validate = new Regex(patten);
if (!validate.IsMatch(input))
{
flag =false;
}
return flag;
}
//N栈存放运算数,O栈存放运算符,
static void Calculate(Stack N, Stack O, string exp)
{
string ch, token = "";
for (int p = 0; p < exp.Length; p++)
{
ch = exp.Substring(p, 1);
if (IsNumberic(ch))
token += ch;
if (ch == " " || p == exp.Length - 1)
{
if (IsNumberic(token))
{
N.Push(token);
token = "";
}
}
else if (ch == "+" || ch == "-" || ch == "*" || ch == "/")
O.Push(ch);
if (N.Count==2)
Compute(N, O);
}
}
static void Compute(Stack N, Stack O)
{
int oper1, oper2;
string oper;
oper1 = Convert.ToInt32(N.Pop());
oper2 = Convert.ToInt32(N.Pop());
oper = Convert.ToString(O.Pop());
switch (oper)
{
case "+":
N.Push(oper1 + oper2);
break;
case "-":
N.Push(oper1 - oper2);
break;
case "*":
N.Push(oper1 * oper2);
break;
case "/":
N.Push(oper1 / oper2);
break;
}
}
}
}
通过用栈来计算简单的算术表达式
最新推荐文章于 2022-07-16 18:23:52 发布