Уравнение пользовательской строки, преобразованное в int-ответ C # - PullRequest
0 голосов
/ 08 декабря 2011
Int answer;
String equation = Console.ReadLine();
Console.writeLine("your equation is {0}", equation);

Как мне преобразовать строку в разрешимое уравнение?

Ответы [ 3 ]

7 голосов
/ 08 декабря 2011

Взгляните на NCalc - Оценщик математических выражений для .NET

Это позволит вам делать такие вещи:

var inputString = "2 + 3 * 5";
Expression e = new Expression(inputString);
var result = e.Evaluate();
2 голосов
/ 08 декабря 2011

eval.js:

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

скомпилировать в 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);
    }
}

скомпилировать в 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
0 голосов
/ 08 декабря 2011
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!");
        }
    }
}

ДЕМО

>calc
input expression: 3 * 4 - 2 * 3
your equation is 3 * 4 - 2 * 3
answer is 6
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...