Is there a string math evaluator in .NET?

前端 未结 16 1434
长情又很酷
长情又很酷 2020-11-22 01:01

If I have a string with a valid math expression such as:

String s = \"1 + 2 * 7\";

Is there a built in library/function in .NET that will p

16条回答
  •  悲&欢浪女
    2020-11-22 01:35

    MathNet.Symbolics

    using System;
    using static MathNet.Symbolics.SymbolicExpression;
    using static System.Console;
    using static System.Numerics.Complex;
    using Complex = System.Numerics.Complex;
    
    namespace MathEvaluator
    {
        class Program
        {
            static readonly Complex i = ImaginaryOne;
    
            static void Main(string[] args)
            {
                var z = Variable("z");
                Func f = Parse("z * z").CompileComplex(nameof(z));
                Complex c = 1 / 2 - i / 3;
                WriteLine(f(c));
    
    
                var x = Variable("x");
                Func g = Parse("x * x + 5 * x + 6").Compile(nameof(x));
                double a = 1 / 3.0;
                WriteLine(g(a));
            }
        }
    }
    

    Don't forget to load

    
    

提交回复
热议问题