Simple Calculator#8319

Simple Calculator (Editorial)

The given example is read as a sequence of three tokens: number symbol number. Calculate the answer depending on the arithmetic operation.

Algorithm implementation

Read the input data.

scanf("%d %c %d",&a,&c,&b);

Compute the answer depending on the arithmetic operation.

if (c == '+') res = a + b; 
if (c == '-') res = a - b; 
if (c == '*') res = a * b; 
if (c == '/') res = a / b;

Print the answer.

printf("%d\n",res);

Algorithm implementation — STL

#include <iostream>
#include <string>
using namespace std;

int a, b, res;
char c;

int main(void)
{
  cin >> a >> c >> b;
  if (c == '+') res = a + b;
  if (c == '-') res = a - b;
  if (c == '*') res = a * b;
  if (c == '/') res = a / b;
  cout << res << endl;
  return 0;
}

Java implementation

import java.util.*;

public class Main
{
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in); 
    int a = con.nextInt();
    String ch = con.next();
    int b = con.nextInt();
    
    int res = 0;
    if (ch.equals("+")) res = a + b;
    if (ch.equals("-")) res = a - b;
    if (ch.equals("*")) res = a * b;
    if (ch.equals("/")) res = a / b;

    System.out.println(res);
    con.close();
  }
}

Python implementation

Read the input data.

a, sign, b = input().split()
a = int(a)
b = int(b)

Compute the answer depending on the arithmetic operation.

if sign == "+":
  res = a + b
if sign == "-":
  res = a – b
if sign == "*":
  res = a * b
if sign == "/":
  res = a // b

Print the answer.

print(res)