{ }codelper
type conversionreading n linesP0044

Truncate, floor, round

The first line gives the count n, and the next n lines give one real number x each.
x is an integer or a number with one or two digits after the decimal point (e.g.
7, -3.7, 0.50).
For each x print three integers on one line, separated by single spaces: (1) truncate: drop the fractional part (toward zero, -3.7 → -3); (2) floor: the largest integer not greater than x (-3.7 → -4); (3) round: the integer nearest to x, and on an exact half (.5) the one farther from zero (2.5 → 3, -2.5 → -3).
Write zero as 0, without a sign.

Input
1 ≤ n ≤ 1,000, -1,000 ≤ x ≤ 1,000
Output
n lines, each "truncate floor round"
Example 1 · stdin
4
3.7
-3.7
2.5
-2.5
stdout
3 3 4
-3 -4 -4
2 2 3
-2 -3 -3
Example 2 · stdin
2
-0.4
0.5
stdout
0 -1 0
0 0 1
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

There are three ways to turn a real into an integer, and their names are easy to mix up.
(1) Truncate (toward zero): (int)x in C/C++/Java/C#, Python int(x), JS/TS Math.trunc(x), Craykon Mathf.Quot(x, 1).
(2) Floor (downward): Python math.floor, JS/TS/Java Math.floor, C# Math.Floor, C/C++ floor, Craykon Mathf.Floor.
They agree on positives, so they only differ on negatives — (int)-3.7 is -3 while the floor is -4.
(3) Rounding treats an exact half (.5) differently per language.
C/C++ round() and Craykon Mathf.Round go away from zero (-2.5 → -3), so they are right as is.
Python round() and C# Math.Round() default to ties-to-even (banker's rounding: round(2.5) == 2, round(0.5) == 0), so pass MidpointRounding.AwayFromZero in C#, and in Python take floor(abs(x) + 0.5) and put the sign back.
JS Math.round and Java Math.round round halves up (toward +∞), so Math.round(-2.5) is -2.
The common workaround floor(x + 0.5) fails on negative halves for the same reason.
One more: converting the text "3.7" straight to an integer fails — Python int("3.7") raises ValueError and Java Integer.parseInt throws NumberFormatException — so read it as a real first (float, Double.parseDouble).
Finally, -0: in JS Math.sign(-0.4) * 0 is -0, and console.log(-0) prints "-0", but join and String write "0".
C# Math.Round(-0.4) is also a double -0, printed as "-0" since .NET Core 3.0, so convert with (int) before printing.

Pythonmain.py · 10 lines
import math def round_half_away(x):    # Python의 round()는 딱 반이면 짝수 쪽(round(2.5) == 2)이라 직접 만든다    return int(math.copysign(math.floor(abs(x) + 0.5), x)) n = int(input())for _ in range(n):    x = float(input())    print(int(x), math.floor(x), round_half_away(x))
JavaScriptmain.js · 11 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const out = [];for (let i = 1; i <= n; i++) {  const x = Number(lines[i]);  // Math.round(-2.5)는 -2(위쪽으로)라 크기로 반올림하고 부호를 붙인다  const r = Math.sign(x) * Math.round(Math.abs(x));  // -0은 문자열로 바꾸면 "0"이 된다  out.push([Math.trunc(x), Math.floor(x), r].join(" "));}console.log(out.join("\n"));
TypeScriptmain.ts · 12 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);const out: string[] = [];for (let i = 1; i <= n; i++) {  const x: number = Number(lines[i]);  // Math.round(-2.5)는 -2(위쪽으로)라 크기로 반올림하고 부호를 붙인다  const r: number = Math.sign(x) * Math.round(Math.abs(x));  // -0은 문자열로 바꾸면 "0"이 된다  out.push([Math.trunc(x), Math.floor(x), r].join(" "));}console.log(out.join("\n"));
JavaMain.java · 20 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        StringBuilder out = new StringBuilder();        for (int i = 0; i < n; i++) {            double x = Double.parseDouble(in.readLine().trim());            int t = (int) x;                       // (int)는 0 쪽으로 버린다            int f = (int) Math.floor(x);            // Math.round(-2.5)는 -2라 크기로 반올림하고 부호를 붙인다            int r = (int) Math.round(Math.abs(x)) * (x < 0 ? -1 : 1);            out.append(t).append(' ').append(f).append(' ').append(r).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 22 lines
using System;using System.Globalization;using System.Text; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine());        var out_ = new StringBuilder();        for (int i = 0; i < n; i++)        {            double x = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);            int t = (int)x;                    // (int)는 0 쪽으로 버린다            int f = (int)Math.Floor(x);            // Math.Round의 기본은 짝수 쪽 반올림이라 0에서 먼 쪽을 지정한다            int r = (int)Math.Round(x, MidpointRounding.AwayFromZero);            out_.Append(t).Append(' ').Append(f).Append(' ').Append(r).Append('\n');        }        Console.Write(out_);    }}
C++main.cpp · 14 lines
#include <cmath>#include <iostream> int main() {    int n;    double x;    std::cin >> n;    for (int i = 0; i < n; i++) {        std::cin >> x;        // static_cast<int>는 0 쪽으로 버리고, std::round는 딱 반이면 0에서 먼 쪽이다        std::cout << static_cast<int>(x) << ' ' << static_cast<int>(std::floor(x)) << ' '                  << static_cast<int>(std::round(x)) << '\n';    }}
Cmain.c · 14 lines
#include <math.h>#include <stdio.h> int main(void) {    int n;    double x;    scanf("%d", &n);    for (int i = 0; i < n; i++) {        scanf("%lf", &x);        /* (int)는 0 쪽으로 버리고, round()는 딱 반이면 0에서 먼 쪽이다 */        printf("%d %d %d\n", (int)x, (int)floor(x), (int)round(x));    }    return 0;}
Craykonmain.cray · 9 lines
n = Console.ReadLine().ToNumber();for (i = 0; i < n; i++){    x = Console.ReadLine().ToNumber();    버림 = Mathf.Quot(x, 1);    내림 = Mathf.Floor(x);    반올림 = Mathf.Round(x);    Console.WriteLine([버림, 내림, 반올림]);}