6

I have a char stand for an operator,there are four operators(+ - * /) in total.

How i did :

int Compute(char c, int a, int b)
{
    if(c == '+')  
        return a+b;
    else if(c == '-')     
        return a-b;
    else if(c == '*')
        return a*b;
    else (c == '/')
        return a/b;
}

Is there a more convenient way to do this?

Superxy
  • 147
  • 1
  • 8
  • 3
    I think the answer is NO. – Sahi Jan 22 '16 at 10:14
  • 3
    what do you mean by 'more convenient' ? – shock_gone_wild Jan 22 '16 at 10:17
  • Possible duplicate of [is there a way i can convert an operator as a char "+" into the actual operator for arithmetic?](http://stackoverflow.com/questions/19242330/is-there-a-way-i-can-convert-an-operator-as-a-char-into-the-actual-operator) – Henrik Jan 22 '16 at 13:25

3 Answers3

4

You could use a switch statement:

int Compute(char c, int a, int b)
{
    switch (c) {  
    case '+': return a+b;
    case '-': return a-b;
    case '*': return a*b;
    case '/': return a/b;
    default: throw std::runtime_error("No such operator");
    }
}
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
0

Firstly, the syntax

else (a == '/')
    return a/b;

is wrong, and should be

else if (a == '/')
    return a/b;

Secondly, your a parameter can only take 4 discrete values, so good practice is to use an enumeration, e.g.

enum Operation
{
    kAddition,
    kSubtraction,
    kMultiplication,
    kDivision
};

int Compute(Operation a, int a, int b)
{
    if (a == kAddition)  
        return a+b;
    else if (a == kSubtraction)     
        return a-b;
    else if (a == kMultiplication)
        return a*b;
    else if (a == kDivision)
        return a/b;
}

which ensures that the user of Compute will only use one of those four values for the operation (a) parameter.

I probably haven't used best practices in my example, so I recommend you read this answer for more detail.

Finally you could make the code more concise by using a switch statement:

enum Operation
{
    kAddition,
    kSubtraction,
    kMultiplication,
    kDivision
};

int Compute(Operation a, int a, int b)
{
    switch (a)
    {
        case kAddition:
            return a+b;
        case kSubtraction:
            return a-b;
        case kMultiplication:
            return a*b;
        case kDivision:
            return a/b;
    }
}
Community
  • 1
  • 1
Archimaredes
  • 1,397
  • 12
  • 26
0
int ComputeByChar(char a, int c, int b)
{ 
    switch(a)
    {
    case '+': return c+b; 
    case '-': return c-b;
    case '/': return c/b;
    case '*': return c*b;
    default: cout<< "Invalid";
        break;
    }
    return 0;
}
Akhil V Suku
  • 870
  • 2
  • 13
  • 34
  • While this can answer the question, it's better to provide some explanations about how this code help. – vard Jan 22 '16 at 11:12