求实现四则运算算法?

znull 2004-10-24 09:46:29
在文本输入任意的运算 如:(512+100)/300
如何模拟运算规则得到正确的结果?谢谢
...全文
139 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Yok 2004-10-24
  • 打赏
  • 举报
回复
以前有人做过比较,用codedom效率太低.简单运算用vsa.jscript最好
popcorn 2004-10-24
  • 打赏
  • 举报
回复
see:

http://www.odetocode.com/Code/80.aspx

http://www.codeproject.com/csharp/runtime_eval.asp
popcorn 2004-10-24
  • 打赏
  • 举报
回复
调用:Evaluator.EvalToDouble("(512+100)/300");

using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.JScript;

namespace mysoft
{
public class Evaluator
{
public static int EvalToInteger(string statement)
{
string s = EvalToString(statement);
return int.Parse(s.ToString());
}

public static double EvalToDouble(string statement)
{
string s = EvalToString(statement);
return double.Parse(s);
}

public static string EvalToString(string statement)
{
object o = EvalToObject(statement);
return o.ToString();
}

public static object EvalToObject(string statement)
{
return _evaluatorType.InvokeMember(
"Eval",
BindingFlags.InvokeMethod,
null,
_evaluator,
new object[] { statement }
);
}

static Evaluator()
{
ICodeCompiler compiler;
compiler = new JScriptCodeProvider().CreateCompiler();

CompilerParameters parameters;
parameters = new CompilerParameters();
parameters.GenerateInMemory = true;

CompilerResults results;
results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource);

Assembly assembly = results.CompiledAssembly;
_evaluatorType = assembly.GetType("Evaluator.Evaluator");

_evaluator = Activator.CreateInstance(_evaluatorType);
}

private static object _evaluator = null;
private static Type _evaluatorType = null;
private static readonly string _jscriptSource =

@"package Evaluator
{
class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr);
}
}
}";
}
}

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧