日期:2014-05-18  浏览次数:20926 次

C# 计算器
如何实现计算器的四则运算?括号

------解决方案--------------------
DataTable dt =new DataTable();
dt.Compute("1+3");
------解决方案--------------------
google的~~
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.CSharp;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> ExpList = new List<string>()
{
"23 + 56 * 2",
"Math.Pow(2, 2)",
"Math.Pow(2, 0.5)",
"(3 + 5) * 2 - 7",
"1.0 / 3.0 + 7",
"((2 + 5) * 2 + (4 * 50)) * 30 - 1",
"-10 * 10 - 9",
"2 / 10.0 - 4",
"3.14 * 3.14 * 2",
"2 << 4"
};
ExpList.ForEach(i => Console.WriteLine(i + " = " + ExpCalc.Calc(i)));

string expwithvar = "(@a + @b) * 10";
double rexpwithvar = ExpCalc.Calc(expwithvar, new Tuple<string, string>("a", "10"), new Tuple<string, string>("b", "5"));
Console.WriteLine(rexpwithvar);

/*
output:
23 + 56 * 2 = 135
Math.Pow(2, 2) = 4
Math.Pow(2, 0.5) = 1.4142135623731
(3 + 5) * 2 - 7 = 9
1.0 / 3.0 + 7 = 7.33333333333333
((2 + 5) * 2 + (4 * 50)) * 30 - 1 = 6419
-10 * 10 - 9 = -109
2 / 10.0 - 4 = -3.8
3.14 * 3.14 * 2 = 19.7192
2 << 4 = 32
150
*/

}
}

class ExpCalc
{
private static Random rnd = new Random();

private static string RandomString(string CharList = "abcdefghijklmnopqrstuvwxyz", int length = 1)
{
string rndstr = "";
for (int i = 1; i <= length; i++)
{
rndstr += CharList.Substring(rnd.Next(0, CharList.Length), 1);
}
return rndstr;
}

private static string RenderText(string Template, Dictionary<string, string> Params)
{
string result = Template;
foreach (var item in Params)
{
result = result.Replace("@" + item.Key, item.Value);
}
return result;
}

public static double Calc(string exp)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters cps = new CompilerParameters();
cps.GenerateExecutable = false;
cps.GenerateInMemory = true;
string classSource = "using System;\n" +
"class @classname\n" +
"{\n" +
"\tpublic double Eval { get { return @exp; } } \n" +
"}";
Dictionary<string, string> renderparams = new Dictionary<string, string>();
string classname = RandomString(length: 10);
renderparams.Add("classname", classname);
renderparams.Add("exp", exp);
classSource = RenderText(classSource, renderparams);
CompilerResults result = provider.CompileAssemblyFromSource(cps, classSource);
Assembly assembly;