Link to home
Start Free TrialLog in
Avatar of kallzz
kallzz

asked on

Evaluate an Algebraic Expression

How to evaluate a algebraic expression if it is available as
a pointer to string ... in C++
for eg
 char * szAlgebra=40+30*25*30/5*25-35
Avatar of Telumehtar
Telumehtar

This can be as complex or as easy as you want (or need) to make it. The 2 options that I see open to you are...

1. Download an external 'Mathematics' library that can do the work for you. I believe that you may want to look at 'bc', which is a standard program on unix/linux machines - but undoubtedly has a windows port also.  I'm not entirely sure if it has a 'library' version or whether you would have to call the BC exe from your code (a bit ugly), but it certainly could do the job. Failing that - you could search for an alternative library to link with your code.

2. If you only need to do 'simple algebra', and only want a restricted set of algebraic commands at your disposal - you could write the routines to do this yourself. The process would have to go something like...

- First, you will want to extract each expression that sits in Paranthesis so that you can evaluate them first.  Iterate through your string and look for an opening bracket - then find the corresponding closing bracket (but not just the next right bracket). Then run this same function on that sub-string, which will (just before it finishes) replace the value from the original string as the result of what was in the brackets.

- Next, go through the string and replace each 'mathematical element' of the expression with what it equals.  You could extract each operation as another string, or you could be clever and do it as a cunning object like a structure containing (number1, operation, number2). You will have to do this in the correct mathematical order for it to be correct.  ([B]inary, [O]perations?, [D]ivision, [M]ultiplication, [A]ddition, [S]ubtraction).

- When you've evaluated every operation in a string (/,*,+,-) you will then have just a number remaining. If this was a 'bracketed expression', put the number into the original expression and remove the brackets from it - and continue to work on the parent expression.  If this is the parent expression - you've got your answer!

A little complex, but I hope this explains it right!
Avatar of kallzz

ASKER

We have to take care of precedance if there is no bracket
ASKER CERTIFIED SOLUTION
Avatar of modulo
modulo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial