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?
Character arithmetic is used to implement arithmetic operations like addition and subtraction on characters in C language. It is used to manipulate the strings. When the characters are used with the arithmetic operations, it converts them into integer value automatically i.e. ASCII value of characters.
I'm sorry, but you can't convert a char to an operator. If you want to take different actions depending on the input, you must branch. You can make your switch more compact though, as noted by Matteo Italia and Jens Gustedt.
Yes - the user gives an input, which is a char or a String or something, which is interpreted as operator by your calculator.
Another way is to use an external program, like bc: char op = '+'; std::string s; s += "6"; s += op; s += "4"; system(("echo " + s + "|bc"). c_str()); If you want to use the result later, check the popen function or the C++ equivalent.
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With