[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1007
  • Last Modified:

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
0
kallzz
Asked:
kallzz
  • 2
1 Solution
 
TelumehtarCommented:
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!
0
 
kallzzAuthor Commented:
We have to take care of precedance if there is no bracket
0
 
kallzzAuthor Commented:
0
 
moduloCommented:
PAQed with points refunded (200)

modulo
Community Support Moderator
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now