基于文本的基本公式计算器功能/类 [英] Text Based Basic Formula Calculator Function/Class

查看:115
本文介绍了基于文本的基本公式计算器功能/类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在寻找类似的东西

int Result; 
DataTable dt2 = new DataTable();
var v = dt2.Compute("3+2-34*12", "");
Result=Convert.ToInt32(v);

上面的代码,用于解决文本基础公式.不幸的是,以上代码仅适用于某些基本运算符(+,-,/,*).需要稍微复杂一点(至少像平方根,^).

the code above, which solves the text base formula. Unfortunately, the code above only works for some basic operators (+,-,/,*). Need a little more complex one (like squareroot, ^ at least).

您能帮我找到一些解决问题的方法吗?

Could you help me to find something tosolve for a little more complex equations?

推荐答案

您可以使用Roslyn

You can use Roslyn scripting API for that. Add Microsoft.CodeAnalysis.CSharp.Scripting package and evaluate C# code like this:

static async Task<double> EvaluateFormulaAsync(string formula)
{
    return await CSharpScript.EvaluateAsync<double>(formula,
        ScriptOptions.Default.WithImports("System.Math"));
}

用法:

var result = EvaluateFormulaAsync("Sqrt(2) + 2 * 15").Result; // 31.4142135623731

注意:脚本API需要.NET Framework 4.6+或.NET Core 1.1

Note: Scripting API requires .NET Framework 4.6+ or .NET Core 1.1

这篇关于基于文本的基本公式计算器功能/类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆