I tried to make a code that calculates the values of the formulas the user inputs. I.e , if user inputs “10+5” , the program would print “The sum is 15” etc. At first, i thought this is a easy thing to do, but if realized that just using scanf orsth wouldn’t do the trick. Then i messed around with arrays and loops to see if the loop encounters “-” or “+” signs in input and then saving the character before “-” or “+” and after it and then calculating it, but i couldnt make this work either.
Could you please lead me in the right direction on how to get this done.
Thank you very much!
I tried to make a code that calculates the values of the formulas the
Share
This can be quite complicated, especially when you get to operator precedence and you need to correctly calculate, for example,
2 + 5 * 6, which needs to be treated as2 + (5 * 6). The correct way to approach this is to construct an expression tree (just like a compiler would). e.g.You do this by creating binary tree. Each nodes holds an operation and (up to) two subnodes. Then you evaluate your expression by traversing the expression tree.