CSpadawan
CSpadawan

Reputation: 115

String expressions with four operators

CS Student here. I want to be able to take a string such as '2+2*3/2-2' and evaluate it (= 3). But I'm not sure how to structure the code to follow the proper order of operations. Here's code for multiplication and division:

int r = 1;
    int n = 0;
    char op = '*';

    for (int i = 0; i < E.length(); i++)
        if (E.charAt(i)=='*'||E.charAt(i)=='/')
        {
            if (op == '*')
                r *= n;
            else
                r /= n;
            n = 0;
            op = E.charAt(i);
        }
        else
            n = n*10 + (E.charAt(i)-'0');

    if (op == '*')
        r *= n;
    else
        r /= n;

    return r;

Thanks for reading!

Upvotes: 0

Views: 76

Answers (4)

Chris Dodd
Chris Dodd

Reputation: 126203

You need to parse the expression. A simple recursive descent parser can do that:

double expression(const char **p) {
    double rv = term(p);
    while (**p) {
        if (**p = '+') {
            ++*p;
            rv += term(p)
        } else if (**p = '-') {
            ++*p;
            rv -= term(p);
        } else
            break; }
    return rv; }

double term(const char **p) {
    double rv = factor(p);
    while (**p) {
        if (**p = '*') {
            ++*p;
            rv *= factor(p)
        } else if (**p = '/') {
            ++*p;
            rv /= factor(p);
        } else
            break; }
    return rv; }

double factor(const char **p) {
    return strtod(p, (char **)&p);
}

Of course, the above won't deal with spaces in the strings, or parenthesis, or other things you might care about, but they can be added relatively easily.

Upvotes: 0

Luke
Luke

Reputation: 1306

Use Reverse Polish Notation to represent your formula in a "computation friendly" form. You can read about RPN here: http://en.wikipedia.org/wiki/Reverse_Polish_notation

RPN version of your 2+2*3/2-2 would be 2 2 3 * 2 / 2 - +

Then the algorithm is like that: Assume each sign from RPN version is an element from the array of symbols. You take element from the array and if this is a number put it on a stack if this is an operator take two elements from the stack and perform operation. The result should land on the stack again. Repeat until you reach the last element of the array. At the end there will be only one element on your stack which is your answer.

Let's visualize: iteration# symbol stack content 1# 2 -> 2 2# 2 -> 2,2 3# 3 -> 3,2,2 4# * -> 6,2 5# 2 -> 2,6,2 6# / -> 3,2 7# 2 -> 2,3,2 8# - -> 1,2 9# + -> 3

Upvotes: 0

jropella
jropella

Reputation: 589

This is exactly what the Interpreter pattern is meant to do. Your mathematical operations are basically a grammar - all you need to do is represent that grammar. Use the Interpreter pattern to parse your mathematical statement, and then use what it spits out to perform the necessary operations.

Upvotes: 0

MadConan
MadConan

Reputation: 3767

Use a binary tree where each node is an arithmetic operator and the leaves are the values.

Upvotes: 2

Related Questions