using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleCalc
{
class Expression
{
string expr;
double ans;
delegate double Calc(double a, char o, double b);
Calc calc = delegate(double a, char o, double b)
{
switch (o)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
case '%': return a%b;
default: return 0;
}
};
public double Ans { get { return ans; } }
public Expression(double res=0)
{
if (String.IsNullOrEmpty(expr)) GetExpr();
if (expr.Contains("Ans")) expr=expr.Replace("Ans", res.ToString());
while(!expr.Contains("quit"))
{
if (expr.Contains("calculate "))
{
expr = expr.Remove(0, 10);
if (expr.Any(c => char.IsLetter(c))) throw new Exception("Bad expression");
if (String.IsNullOrWhiteSpace(expr)) throw new Exception("Bad expression");
ans = Calculate();
Console.WriteLine("Ans={0}",ans);
try
{
Expression str = new Expression(ans);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
else throw new Exception("Bad expression");
}
}
public Expression(string expr)
{
this.expr = expr;
}
public void GetExpr()
{
Console.Write("> ");
expr = Console.ReadLine();
}
public double Calculate()
{
int index;
int i=expr.Length,len = 0;
Stack<int> brackets = new Stack<int>();
do
{
i--;
if (expr[i] == ')') brackets.Push(i);
if (expr[i] == '(')
{
len = brackets.Pop() - i;
if (brackets.Count == 0)
{
Expression e0 = new Expression(expr.Substring(i + 1, len - 1));
expr=expr.Remove(i, len+1);
expr = expr.Insert(i, (e0.Calculate()).ToString());
}
}
} while (i > 0);
index=expr.IndexOfAny(new char[]{ '+', '-' });
if (index > 0)
{
Expression e1 = new Expression(expr.Substring(0, index));
Expression e2 = new Expression(expr.Substring(index + 1));
expr = calc(e1.Calculate(), expr[index], e2.Calculate()).ToString();
}
else
{
index = expr.IndexOfAny(new char[] { '*', '/', '%' });
if (index > 0)
{
Expression e1 = new Expression(expr.Substring(0, index));
Expression e2 = new Expression(expr.Substring(index + 1));
expr = calc(e1.Calculate(), expr[index], e2.Calculate()).ToString();
}
}
try
{
ans = Convert.ToDouble(expr);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return ans;
}
}
class Program
{
static void Main(string[] args)
{
try
{
Expression str = new Expression();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Bye");
Console.Read();
}
}
}
Comments
Leave a comment