简体   繁体   中英

Evaluating a mathematical expression in C++

In a coding problem I've been working on for some time now, I've come to a step where I have to evaluate a mathematical expression that looks like this :

3 * 2 ^ 3 ^ 2 * 5

and should be evaluated like this :

3 * 2 ^ 3 ^ 2 * 5 = 3 * 2^(3 * 2) * 5 = 3 * 64 * 5 = 960.

In the current form of my implementation, I have two vectors, one contains the operands as integers, while the other one contains the operators as chars.

For the current case, they would be : vector<int> operands = { 3, 2, 3, 2, 5 } and vector<char> operators = { '*', '^', '^', '*' } .

This is just a sample case, the order of operations may differ in the sense that multiplication might not always be the first/last operation to be performed.

I've been stuck at this particular step for a while now, namely evaluating the expression encapsulated by the two vector containers to an integer. I've looked at some mathematical parsers I could find on the web, but I still don't see how to implement a proper evaluation.

A solution would be very much appreciated.

在此处输入图片说明

What you would like is possible with expression templates . They make it possible to evaluate expressions in non-standard order and/or behavior - using them you can also define multiple meaning for the same operator in an expression.

Simply compute the value as you parse the expression, maintaining one variable for the final product and one for the current multiplicand (ie the current group of exponents with the corresponding base). Apply each exponential operand sequentially as you see it, thus performing left-associative exponentiation.

As an aside, I wouldn't bother storing the entire expression in some kind of vectorized format; I see no useful reason for doing so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM