{ }codelper
switchinteger divisionP0021

Four-operation calculator

One line gives "a op b" separated by single spaces, where op is one of +, -, *, /.
Print the result as an integer.
/ is integer division and the fractional part of the quotient is dropped toward zero (7 / 2 = 3, -7 / 2 = -3, 7 / -2 = -3).
For / with b equal to 0, print "error".

Input
-1,000,000 ≤ a, b ≤ 1,000,000 (integers); op is one of +, -, *, /
Output
one integer, or "error"
Example 1 · stdin
-7 / 2
stdout
-3
Example 2 · stdin
1000000 * 1000000
stdout
1000000000000
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

The direction of negative division differs.
In C, C++, Java and C#, integer / truncates toward zero, so -7 / 2 == -3, but Python's // floors, giving -4.
In Python use abs(a) // abs(b) with the sign put back, or int(a / b) (exact within this problem's range).
JS/TS / is always floating-point, so Math.trunc(a / b) is right and Math.floor falls into the same trap as Python.
Craykon's / also gives 3.5, so use Mathf.Quot(a, b) (truncates toward zero).
Products reach one trillion, so int in C, Java and C# (about 2.1 billion max) overflows — use long long/long.
Guard division by zero first: Java throws ArithmeticException, C# throws DivideByZeroException, C and C++ have undefined behavior (usually a crash), JS gives Infinity/NaN.
Branching: switch in C, C++, Java, C#, JS; match in Python 3.10+.
Craykon writes switch (op) { case "+": … default: … } and, like C#, never falls through to the next case (the final break; is optional).
In C, C++, Java and JS a missing break runs into the next case.
In JS 0 * -5 is -0 and console.log(-0) prints -0, so print String(…).

Pythonmain.py · 16 lines
a, op, b = input().split()a, b = int(a), int(b)match op:    case "+":        print(a + b)    case "-":        print(a - b)    case "*":        print(a * b)    case "/":        if b == 0:            print("error")        else:            # Python의 // 는 내림(-7 // 2 == -4)이라 크기로 나눈 뒤 부호를 붙인다            q = abs(a) // abs(b)            print(q if (a < 0) == (b < 0) else -q)
JavaScriptmain.js · 12 lines
const [x, op, y] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);const a = Number(x);const b = Number(y);let result;switch (op) {  case "+": result = a + b; break;  case "-": result = a - b; break;  case "*": result = a * b; break;  case "/": result = b === 0 ? "error" : Math.trunc(a / b); break;}// String(-0) 은 "0" (console.log(-0) 은 "-0"을 찍는다)console.log(String(result));
TypeScriptmain.ts · 13 lines
import { readFileSync } from "node:fs";const [x, op, y]: string[] = readFileSync(0, "utf8").trim().split(/\s+/);const a: number = Number(x);const b: number = Number(y);let result: number | string = "";switch (op) {  case "+": result = a + b; break;  case "-": result = a - b; break;  case "*": result = a * b; break;  case "/": result = b === 0 ? "error" : Math.trunc(a / b); break;}// String(-0) 은 "0" (console.log(-0) 은 "-0"을 찍는다)console.log(String(result));
JavaMain.java · 18 lines
import java.util.Scanner; public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        long a = sc.nextLong();        String op = sc.next();        long b = sc.nextLong();        String result = switch (op) {            case "+" -> String.valueOf(a + b);            case "-" -> String.valueOf(a - b);            case "*" -> String.valueOf(a * b);            case "/" -> b == 0 ? "error" : String.valueOf(a / b);            default -> "";        };        System.out.println(result);    }}
C#Main.cs · 20 lines
using System; class Program{    static void Main()    {        string[] t = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);        long a = long.Parse(t[0]);        long b = long.Parse(t[2]);        string result = t[1] switch        {            "+" => (a + b).ToString(),            "-" => (a - b).ToString(),            "*" => (a * b).ToString(),            "/" => b == 0 ? "error" : (a / b).ToString(),            _ => "",        };        Console.WriteLine(result);    }}
C++main.cpp · 16 lines
#include <iostream> int main() {    long long a, b;    char op;    std::cin >> a >> op >> b;    switch (op) {        case '+': std::cout << a + b << "\n"; break;        case '-': std::cout << a - b << "\n"; break;        case '*': std::cout << a * b << "\n"; break;        case '/':            if (b == 0) std::cout << "error\n";            else std::cout << a / b << "\n";            break;    }}
Cmain.c · 17 lines
#include <stdio.h> int main(void) {    long long a, b;    char op;    scanf("%lld %c %lld", &a, &op, &b);    switch (op) {        case '+': printf("%lld\n", a + b); break;        case '-': printf("%lld\n", a - b); break;        case '*': printf("%lld\n", a * b); break;        case '/':            if (b == 0) puts("error");            else printf("%lld\n", a / b);            break;    }    return 0;}
Craykonmain.cray · 26 lines
t = Console.ReadLine().Split();a = t[0].ToNumber();op = t[1];b = t[2].ToNumber();switch (op){    case "+":        Console.WriteLine(a + b);        break;    case "-":        Console.WriteLine(a - b);        break;    case "*":        Console.WriteLine(a * b);        break;    default:        if (b == 0)        {            Console.WriteLine("error");        }        else        {            Console.WriteLine(Mathf.Quot(a, b));        }        break;}