Text Based Basic Formula Calculator Function/Class

左心房为你撑大大i 提交于 2019-12-12 02:34:23

问题


Looking for something like

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?


回答1:


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"));
}

Usage:

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

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



来源:https://stackoverflow.com/questions/43552723/text-based-basic-formula-calculator-function-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!