0

For my exam, I want to do a project in C++, a program that is solving mathematical functions. I mean, if I read from keyboard 2*x*x+3*x+4, and x is, i don't know, 3, i want to display 31. I think I might use strings, or character sequence, and if the character is a number and next character is * and the next is x, to do the operation, and if the next character is +, I don't know, I'm stuck. Do you have any suggestions about this algorithm?

Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
  • Shunting yard with support for variables would do it. – jdphenix May 09 '15 at 05:46
  • Try by reading the expression character by character , checking for the operators and replacing "x" with the numeric value .. – Ajay May 09 '15 at 06:02
  • 1
    To the OP. Whatever you do, don't do it in the way you suggested. That is a naive, error prone, and curse-inducing way of writing a parser for mathematical expressions. Add parentheses, order of operations, and you will go nuts doing it the naive way. There are formal ways of doing such things such as building a tree, recursive descent parser, etc. – PaulMcKenzie May 09 '15 at 06:08
  • 1
    This is possibly not as trivial as it might sound. When you consider parsing, order of precedence of the math functions and then interpreting the results. – Galik May 09 '15 at 06:08
  • I think about using the polish forms, but maybe is a different way, a better way, to solve this problem. – Rosca Alin May 09 '15 at 06:34
  • 2
    @RoscaAlin This has been done many times before for C++. My suggestion to you is to see how these are implemented. The reason you should look at existing implementations is that you will get the idea of the techniques used to accomplish expression parsing. I will tell you this -- none of them did it by naively scanning the string and figuring out where the 'x' is. Once you get an inventory of the various techniques, then you have a foundation of how to start and finish your project. http://stackoverflow.com/questions/11703082/parsing-math-expression-in-c-c – PaulMcKenzie May 09 '15 at 06:46

0 Answers0