Convert char to arithmetic operator

I have a char stand for the operator, there are only four operators (+ - * /).

How I did it:

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

Is there a more convenient way to do this?

+5
source share
3 answers

You can use the switch statement:

 int Compute(char c, int a, int b) { switch (c) { case '+': return a+b; case '-': return ab; case '*': return a*b; case '/': return a/b; default: throw std::runtime_error("No such operator"); } } 
+4
source

First, the syntax

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

wrong and should be

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

Secondly, your parameter a can take only 4 discrete values, so it is good practice to use an enumeration, for example

 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 ab; else if (a == kMultiplication) return a*b; else if (a == kDivision) return a/b; } 

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

I probably have not used the best practices in my example, so I recommend that you read this answer for more details.

Finally, you can make the code shorter using the 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 ab; case kMultiplication: return a*b; case kDivision: return a/b; } } 
0
source
 int ComputeByChar(char a, int c, int b) { switch(a) { case '+': return c+b; case '-': return cb; case '/': return c/b; case '*': return c*b; default: cout<< "Invalid"; break; } return 0; } 
0
source

Source: https://habr.com/ru/post/1241213/


All Articles