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

假设一个字符串str="4*36+7+88/12^2",C#如何直接计算出这个字符串变量str的算术值。
假设一个字符串str="4*36+7+88/12^2",C#如何直接计算出这个字符串变量str的算术值。

------解决方案--------------------
C# code
public static object Eval(string AExpression)
{
    try
    {
        return new DataTable().Compute(AExpression, "");
    }
    catch
    {
        return null;
    }
}

------解决方案--------------------
楼上有个问题,乘方在C#可不是这么表示阿,四则运算楼上是对的
------解决方案--------------------
C# code
// SuperCalc.cs - 超级计算器

using System;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.VisualBasic;
using System.Reflection;
using System.Text;
using System.Globalization;

namespace Skyiv
{
  class SuperCalc : Form
  {
    TextBox tbxA1;
    TextBox tbxA3;

    [STAThread]
    static void Main(string [] args)
    {
      Application.Run(new SuperCalc());
    }

    SuperCalc()
    {
      Text              = "Super Calculator";
      StartPosition     = FormStartPosition.CenterScreen;
      Width             = 300;
      Height            = 300;

      tbxA1             = new TextBox();
      tbxA1.Parent      = this;
      tbxA1.Multiline   = true;
      tbxA1.WordWrap    = false;
      tbxA1.Dock        = DockStyle.Fill;
      tbxA1.BorderStyle = BorderStyle.FixedSingle;

      Panel pnlA1       = new Panel();
      pnlA1.Parent      = this;
      pnlA1.Height      = 22;
      pnlA1.Dock        = DockStyle.Top;

      tbxA3             = new TextBox();
      tbxA3.Parent      = pnlA1;
      tbxA3.Dock        = DockStyle.Fill;
      tbxA3.BorderStyle = BorderStyle.FixedSingle;
      tbxA3.ReadOnly    = true;

      Button btnA3      = new Button();
      btnA3.Text        = "&Calculate";
      btnA3.Parent      = pnlA1;
      btnA3.Width       = 80;
      btnA3.Dock        = DockStyle.Left;
      btnA3.Click      += new EventHandler(Calc_Clicked);
    }

    void Calc_Clicked(object sender, EventArgs ea)
    {
      (sender as Control).Enabled = false;
      try
      {
        tbxA3.Text = (new Expression(tbxA1.Text)).Compute().ToString();
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message, "Error");
      }
      finally
      {
        (sender as Control).Enabled = true;
      }
    }
  }


  // VBExpression.cs - 动态生成数学表达式并计算其值
  // 表达式使用 Visual Baisc 语法
  // 可使用 pi、e 等常量,sin、cos、tan、log、sqrt 等函数

  sealed class Expression
  {
    object instance;
    MethodInfo method;

    public Expression(string expression)
    {
      if (expression.ToUpper(CultureInfo.InvariantCulture).IndexOf("RETURN") < 0)
      {
        expression = "Return " + expression.Replace(Environment.NewLine, " ");
      }
      string className = "Expression";
      string methodName = "Compute";
      CompilerParameters p = new CompilerParameters();
      p.GenerateInMemory = true;
      CompilerResults cr = new VBCodeProvider().CompileAssemblyFromSource
      (
        p,
        string.Format
        (
          @"Option Explicit Off
          Option Strict Off
          Imports System, System.Math, Microsoft.VisualBasic
          NotInheritable Class {0}
          Public Function {1} As Double
          {2}
          End Function
          End Class",
          className, methodName, expression
        )
      );
      if(cr.Errors.Count > 0)
      {
        string msg = "Expression(\"" + expression + "\"): \n";
        foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
        throw new Exception(msg);
      }
      instance = cr.CompiledAssembly.CreateInstance(className);
      method = instance.GetType().GetMethod(methodName);
    }

    public double Compute()
    {
      return (double)method.Invoke(instance, null);
    }
  }
}