Superxy
Superxy

Reputation: 147

convert char to arithmetic operator

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?

Upvotes: 6

Views: 4730

Answers (3)

Akhil V Suku
Akhil V Suku

Reputation: 912

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;
}

Upvotes: 0

TartanLlama
TartanLlama

Reputation: 65600

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");
    }
}

Upvotes: 4

Archimaredes
Archimaredes

Reputation: 1427

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;
    }
}

Upvotes: 0

Related Questions