开发者

entering a string to be used as a formula , in c#

开发者 https://www.devze.com 2023-04-10 21:51 出处:网络
I\'ve found the shunting yard algorithm, butit feels like case is a little bit different. What if the formula your entering has variables that you want to use in another formula

I've found the shunting yard algorithm, but it feels like case is a little bit different. What if the formula your entering has variables that you want to use in another formula

you enter

cout<<"enter string"<<endl;
cin>>f;
开发者_如何学C

and you enter f as

3 * (X*X) + 2*X + 7 

and you use that string and parse it to find the root, for example.


While it is hard to understand what you are looking for, it hints at the ability to evaluate strings as formulas. If your looking for an Eval like solution, take a look at nCalc. Stealing from their webpage:

Expression e = new Expression("2 + 3 * 5");
Debug.Assert(17 == e.Evaluate());

It also allows you to use parameters, like

e.Parameters["X"] = 10;

and then use X as part of your string to evaluate.

It let's you convert a string representing a formula into it's final value. If you are not asking about interpreting strings at formulas then I am at a loss for what you are asking. I recommend revising your question to better articulate the inputs and outputs of your proposed functionality.


One solution that comes to my mind is, may be you can create a valid C# code from that string at runtime and make it compile, and make it execute. For example your code cam become in memory like

using namespace FormulaCalculator
{
     public class Calculator 
     {
         public static object Calculate() 
         {
             return 3 * (X*X) + 2*X + 7 ; //where X is replaced value at runtime.
         }
     }
}

Compile this with CodeDome in in-memory assembly and run. Here an example Example

object resultOfFormula = FormulaCalculator.Calculator.Calculate()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号