I am attempting to write a program that evaluates a mathematical expression after parsing it. I have the parser correct, using a string to strip it into tokens and compare it to grammar rules to validate the expression. It should be able to evaluate expressions of type
(3+2)*4+-1= where negative numbers are included. I am having a tough time with the evaluation part.

string result;
string token1;
string token2;
double c=0;
double d=0;
stack<double> nums;

for(int i=0; i<exp.size();i++)
	token1= exp.at(i);
	{ c= atof (token1.c_str());
	switch(s_mapStringValues[token1])			//
	       case PLUS:
	       case MINUS:
	       case MUL:
	       case DIV:


Using the idea of pushing the number onto a stack and then popping last two and evaluating when finding an operator does not work when I have two operators following each other as 3*-4. Any ideas around this?

7 Years
Discussion Span
Last Post by maverick0612

3*-4. Any ideas around this?

In the evaluation of polynomial expressions, it is safe to treat all " - " minus signs as preceding negative numbers (it is safe to assume there is no subtraction). The only special case one must consider is the case of the double negative, wich can be easily tested for.


-3x^2-4x = -5

Can trasnlate to:

Negative Three x squared plus negative four x = negative 5

Notice that there is no "subraction" involved with the evaluation of polynomials. With the exception of the double negative, you can safely assume all minus signs are only to identify negative values.

If your program supports only the basic math operations (addition, subraction, multiplication and division) between your polynomial terms, then all you really have to identify is * multiplication and / division... everything else is addition.

Edited by Clinton Portis: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.