问题
Int answer;
String equation = Console.ReadLine();
Console.writeLine("your equation is {0}", equation);
How do I convert the string into a solvable equation?
回答1:
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();
回答2:
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
回答3:
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
来源:https://stackoverflow.com/questions/8426218/user-input-string-equation-converted-to-an-int-answer-c-sharp