Algorithm 16 - Basic Mathematical Operations

Q.

Description:
Your task is to create a function that does four basic mathematical operations.

The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.

Examples
basicOp('+', 4, 7) // Output: 11
basicOp('-', 15, 18) // Output: -3
basicOp('*', 5, 5) // Output: 25
basicOp('/', 49, 7) // Output: 7

A)

int basic_op(char op, int value1, int value2) 
{
  int cul = 0;
  if (op == '+')
    cul = value1 + value2;
  else if (op == '-')
    cul = value1 - value2;
  else if (op == '*')
    cul = value1 * value2;
  else if (op == '/')
    cul = value1 / value2;
  return cul;
}

another solution
int basic_op(char op, int x, int y) 
{
  return op == 43 ? x + y : op == 45 ? x - y : op == 42 ? x * y : x / y;
} -> false 면 다음 기호로 넘어가는 방식. 숫자는 아스키코드로 연산기호들.

좋은 웹페이지 즐겨찾기