C# solve simplest equations

2019-03-31 12:14发布

问题:

In C#, I am looking for a way to solve simple equations like this. Z = A + B

I am trying to build a class that would give me the 3rd parameter if I give any of the 2 others.

Example, given Z=A+B

If you know A=3 and B=6 then you know Z=9

If you know A=4 and Z=8 then you know B=4

How would I best perform these kinds of tasks in software?

The other idea is to use math expressions evaluates, like ncalc. They can interpret math expressions, for example convert 3*(8+2) into 30, but not solve equations like 3*(8+x)=30 --> x=2.

回答1:

Are you sure NCalc wouldn't do what you need? Take a look at an example from http://ncalc.codeplex.com/.

Define parameters, even dynamic or expressions

Expression e = new Expression("Round(Pow([Pi], 2) + Pow([Pi2], 2) + [X], 2)");

e.Parameters["Pi2"] = new Expression("Pi * [Pi]");
e.Parameters["X"] = 10;

e.EvaluateParameter += delegate(string name, ParameterArgs args)
  {
    if (name == "Pi")
    args.Result = 3.14;
  };

Debug.Assert(117.07 == e.Evaluate());

Please note this is untested - but it looks like you could do something like this with NCalc:

var e = new Expression("[A] + [B]"); 
e.Parameters = /* your input */ 
var result = e.Evaluate(); 


回答2:

Try out C# Expression Evaluator , See if it matches your requirements.



标签: c# solver