Simple Math Expression in ExprTk
Asked Answered
C

2

19

I am attempting to use a simple expression such as the following and the result should be that the value of z becomes 1. However nothing seems to be happening any suggestions on how I could resolve this issue ?

template<typename t>
void MyTestB()
{

    t x = 1.0;
    t z = 0;

    std::string e = "if((x + 2) == 3){z=1;}";
    exprtk::symbol_table<t> symbol_table;
    symbol_table.add_variable("x",x);
    symbol_table.add_variable("z",z);

    exprtk::expression<t> expression;
    expression.register_symbol_table(symbol_table);


    exprtk::parser<t> parser;

    parser.compile(e,expression);
    t y = expression.value();
    std::cout << z;
}

The program does finish however at y = NAN (which is understandable because expression is a conditional statement) However z still remains 0. I was expecting it to become 1

Citizenship answered 18/9, 2013 at 14:54 Comment(4)
"nothing seems to be happening" is a somewhat vague problem description. How do you call this function? Do you get wrong outpu or no output at all? Does the program finish or hang?Coronation
Does it work without templates? (e.g. fix t as int)Cervelat
Just glancing at the examples online, it looks like your string should look like: "if((x+2) == 3, z := 1, 0)". Have you tried something like that?Bevins
@Taylor yes that did the trick. Could you put that in the answeCitizenship
B
19

Looking at the examples, it appears that if statements should have the form:

if (condition, expression if true, expression if false)

Also, assignment uses := instead of just =. So you should use the string:

if((x + 2) == 3, z := 1, 0)

Bevins answered 18/9, 2013 at 16:37 Comment(0)
H
2

The expression when written out with proper indentation like so:

if( (x + 2) == 3 )
{
  z=1;
}

The issue is the value of the consequent statement: "z=1".

The = here is not assignment but rather equality (aka '==' ).

Hence the actual result of the if statement when the condition is true is false which converts to zero.

Note: Section 12.3 of the readme documentation details the how the conditional statements operate.

Hospice answered 6/9, 2023 at 6:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.