用户输入字符串方程,转换为int答案C#

Int answer; String equation = Console.ReadLine(); Console.writeLine("your equation is {0}", equation); 

如何将字符串转换为可解的等式?

看看NCalc – .NET的数学表达式评估器

它会让你做这样的事情:

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

编译成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 
 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