0

i was trying to evaluate expression using NCalc,

Expression ex = new Expression("3[X] + 4[Y]");
ex.Parameters["X"] = 10;
ex.Parameters["Y"] = 20;

I have been getting this error:

missing EOF at '[x]' at line 1:1

Not sure why I have getting this error? Does the square brackets for variables have something to do with this?

awh112
  • 1,466
  • 4
  • 22
  • 34
user
  • 91
  • 2
  • 12
  • 1
    I've never used NCalc before, but my guess is that it doesn't support the "nx" multiplication syntax. Try doing `"3 * [X] + 4 * [Y]"` instead. – Abion47 Mar 14 '17 at 18:44
  • That worked. Seriously I missed such a small thing. – user Mar 14 '17 at 18:49

1 Answers1

1

See NCalc's parameters documentation.

Using static parameters:

Expression e = new Expression("2 * [x] ^ 2 + 5 * [y]");
e.Parameters["x"] = 5;
e.Parameters["y"] = 1;

Console.WriteLine(e.Evaluate());

From your example:

Expression ex = new Expression("3 * [X] + 4 * [Y]");
ex.Parameters["X"] = 10;
ex.Parameters["Y"] = 20;

// 110
Console.WriteLine(ex.Evaluate());
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • Is there a way we could evaluate expression even when multiply(*) is not mentioned in expression like "3[X] + 4[Y]" .Also is there a way we could check the format of expression ? – user Mar 14 '17 at 18:54
  • The library doesn't appear to support implicit multiplication. However, you can "build up" expressions if the grammar is too strict for your use case. See [the tests](https://ncalc.codeplex.com/SourceControl/latest#Evaluant.Calculator.Tests/Fixtures.cs). You can check expressions for errors using `Expression.HasError` and `Expression.Error`. – Dustin Kingen Mar 14 '17 at 19:06