c#根据公式进行自动计算的实现

来源:互联网 发布:网络分销的利弊 编辑:程序博客网 时间:2024/05/21 09:51

    一个表达式计算器,用C#写的,利用了VB编译器的强劲性能,可以计算任何合法的VB表达式,可以有一个自变量(x),也可以不要自变量。

   注:CompileAssemblyFromSource()方法需要.net2.0,也就是Visaul Studio 2005。

  1// Calc.cs - 表达式计算器
  2// 编译方法: csc /t:winexe Calc.cs VBExpression.cs
  3
  4using System;
  5using System.Windows.Forms;
  6using Skyiv.Util;
  7
  8namespace Skyiv
  9{
 10  class Calc : Form
 11  {
 12    TextBox tbxA1, tbxA2, tbxA3;
 13
 14    Calc()
 15    {
 16      Text              = "表达式计算器";
 17      StartPosition     = FormStartPosition.CenterScreen;
 18      Width             = 400;
 19      Height            = 200;
 20
 21      Label lblA1       = new Label();
 22      lblA1.Text        = "表达式(&E)";
 23      lblA1.Parent      = this;
 24      lblA1.Top         = 23;
 25      lblA1.Left        = 10;
 26      lblA1.AutoSize    = true;
 27
 28      tbxA1             = new TextBox();
 29      tbxA1.Parent      = this;
 30      tbxA1.Top         = 20;
 31      tbxA1.Left        = 80;
 32      tbxA1.Width       = 300;
 33      tbxA1.BorderStyle = BorderStyle.FixedSingle;
 34
 35      Label lblA2       = new Label();
 36      lblA2.Text        = "自变量(&X)";
 37      lblA2.Parent      = this;
 38      lblA2.Top         = 48;
 39      lblA2.Left        = 10;
 40      lblA2.AutoSize    = true;
 41
 42      tbxA2             = new TextBox();
 43      tbxA2.Parent      = this;
 44      tbxA2.Top         = 45;
 45      tbxA2.Left        = 80;
 46      tbxA2.Width       = 300;
 47      tbxA2.BorderStyle = BorderStyle.FixedSingle;
 48
 49      Button btnA3      = new Button();
 50      btnA3.Text        = "计算(&C)";
 51      btnA3.Parent      = this;
 52      btnA3.Top         = 70;
 53      btnA3.Left        = 10;
 54      btnA3.Width       = 62;
 55      btnA3.Click      += new EventHandler(Calc_Clicked);
 56
 57      tbxA3             = new TextBox();
 58      tbxA3.Parent      = this;
 59      tbxA3.Top         = 70;
 60      tbxA3.Left        = 80;
 61      tbxA3.Width       = 300;
 62      tbxA3.BorderStyle = BorderStyle.FixedSingle;
 63      tbxA3.ReadOnly    = true;
 64
 65
 66      TextBox tbxA4     = new TextBox();
 67      tbxA4.Text        = @"
 68表达式使用 Visual Baisc 语法,可带一个的自变量(x)
 69可使用 pi、e 等常量,sin、cos、tan、log、sqrt 等函数
 70例子:x * cos(x * pi / sqrt(25 * 6^4)) + log(E^10)";
 71      tbxA4.Parent      = this;
 72      tbxA4.Top         = 95;
 73      tbxA4.Left        = 10;
 74      tbxA4.Width       = 370;
 75      tbxA4.Height      = 65;
 76      tbxA4.BorderStyle = BorderStyle.None;
 77      tbxA4.Multiline   = true;
 78      tbxA4.ReadOnly    = true;
 79    }

 80
 81    void Calc_Clicked(object sender, EventArgs ea)
 82    {
 83      (sender as Control).Enabled = false;
 84      try
 85      {
 86        double x = 0;
 87        if (tbxA2.Text.Trim().Length != 0)
 88        {
 89          try
 90          {
 91            x = double.Parse(tbxA2.Text);
 92          }

 93          catch
 94          {
 95            try
 96            {
 97              x = (new Expression(tbxA2.Text)).Compute(0);
 98            }

 99            catch (Exception ex)
100            {
101              MessageBox.Show(ex.Message, "自变量出错");
102            }

103          }

104        }

105        tbxA3.Text = (new Expression(tbxA1.Text)).Compute(x).ToString();
106      }

107      catch (Exception ex)
108      {
109        MessageBox.Show(ex.Message, "表达式出错");
110      }

111      finally
112      {
113        (sender as Control).Enabled = true;
114      }

115    }

116
117    [STAThread]
118    static void Main(string [] args)
119    {
120      Application.Run(new Calc());
121    }

122  }

123}

124


计算表达式的代码用的是“银河”的代码(VB版):
http://www.cnblogs.com/skyivben/archive/2005/10/31/265861.html

 1// VBExpression.cs - 动态生成数学表达式并计算其值
 2// 表达式使用 Visual Baisc 语法,可带一个的自变量(x)
 3// 可使用 pi、e 等常量,sin、cos、tan、log、sqrt 等函数
 4// 例子:e + sqrt(log(pi ^ e) * x) + sin(x * pi / 180)
 5
 6using System;
 7using System.CodeDom.Compiler;
 8using Microsoft.VisualBasic;
 9using System.Reflection;
10using System.Text;
11using System.Globalization;
12
13namespace Skyiv.Util
14{
15  sealed class Expression
16  {
17    object instance;
18    MethodInfo method;
19
20    public Expression(string expression)
21    {
22      if (expression.ToUpper(CultureInfo.InvariantCulture).IndexOf("RETURN"< 0) expression = "Return " + expression;
23      string className = "Expression";
24      string methodName = "Compute";
25      CompilerParameters p = new CompilerParameters();
26      p.GenerateInMemory = true;
27      CompilerResults cr = new VBCodeProvider().CompileAssemblyFromSource
28      (
29        p,
30        string.Format
31        (
32          @"Option Explicit Off
33          Option Strict Off
34          Imports System, System.Math, Microsoft.VisualBasic
35          NotInheritable Class {0}
36          Public Function {1}(x As Double) As Double
37          {2}
38          End Function
39          End Class",
40          className, methodName, expression
41        )
42      );
43      if(cr.Errors.Count > 0)
44      {
45        string msg = "Expression(/"" + expression + "/"): /n";
46        foreach (CompilerError err in cr.Errors) msg += err.ToString() + "/n";
47        throw new Exception(msg);
48      }

49      instance = cr.CompiledAssembly.CreateInstance(className);
50      method = instance.GetType().GetMethod(methodName);
51    }

52
53    public double Compute(double x)
54    {
55      return (double)method.Invoke(instance, new object [] { x });
56    }

57  }

58}

59


 

原创粉丝点击