User input string equation, converted to an int answer C#

天涯浪子 提交于 2019-11-28 02:27:23

Take a look at NCalc - Mathematical Expressions Evaluator for .NET

It'll let you do this sort of thing:

var inputString = "2 + 3 * 5";
Expression e = new Expression(inputString);
var result = e.Evaluate();

eval.js:

package BLUEPIXY {
    class Math {
        static public function Evaluate(exp : String) : double {
            return eval(exp);
        }
    }
}

compile to eval.dll

>jsc /t:library eval.js

calc.cs:

using System;
using System.Text.RegularExpressions;

class Calc {
    static void Main(){
        int? answer = null;
        String equation = Console.ReadLine();
        Console.WriteLine("your equation is {0}", equation);
        if(Regex.IsMatch(equation, @"^[0-9\.\*\-\+\/\(\) ]+$")){
            answer = (int)BLUEPIXY.Math.Evaluate(equation);
        }
        Console.WriteLine("answer is {0}", answer);
    }
}

compile to calc.exe

>csc /r:eval.dll /r:Microsoft.JScript.dll calc.cs

DEMO

>calc
3 * 4 - 2 * 3
your equation is 3 * 4 - 2 * 3
answer is 6
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;

class Sample {
    static void Main(){
        CSharpCodeProvider csCompiler = new CSharpCodeProvider();
        CompilerParameters compilerParameters = new CompilerParameters();
        compilerParameters.GenerateInMemory = true;
        compilerParameters.GenerateExecutable = false;
        string temp =
@"static public class Eval {
    static public int calc() {
        int exp = $exp;
        return exp;
    }
}";
        Console.Write("input expression: ");
        string equation = Console.ReadLine();//need input check!!
        Console.WriteLine("your equation is {0}", equation);
        temp = temp.Replace("$exp", equation);
        CompilerResults results = csCompiler.CompileAssemblyFromSource(compilerParameters,
            new string[1] { temp });

        if (results.Errors.Count == 0){
            Assembly assembly = results.CompiledAssembly;
            MethodInfo calc = assembly.GetType("Eval").GetMethod("calc");
            int answer = (int)calc.Invoke(null, null);
            Console.WriteLine("answer is {0}", answer);
        } else {
            Console.WriteLine("expression errors!");
        }
    }
}

DEMO

>calc
input expression: 3 * 4 - 2 * 3
your equation is 3 * 4 - 2 * 3
answer is 6
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!