{ }codelper
타입 바꾸기n줄 읽기P0044

버리기·내리기·반올림

첫 줄에 수의 개수 n이 주어지고, 다음 n줄에 실수 x가 한 줄에 하나씩 주어진다.
x는 정수이거나 소수점 아래 한두 자리까지 쓴 수다(예: 7, -3.7, 0.50).
각 x마다 정수 세 개를 빈칸 하나로 띄어 한 줄에 출력하라.
① 버림: 소수 부분을 떼어 낸 값(0 쪽으로, -3.7 → -3).
② 내림: x보다 크지 않은 가장 큰 정수(-3.7 → -4).
③ 반올림: x에 가장 가까운 정수이고, 딱 가운데(.5)이면 0에서 먼 쪽(2.5 → 3, -2.5 → -3).
0은 부호 없이 0으로 쓴다.

입력
1 ≤ n ≤ 1,000, -1,000 ≤ x ≤ 1,000
출력
n줄, 줄마다 "버림 내림 반올림"
예시 1 · stdin
4
3.7
-3.7
2.5
-2.5
stdout
3 3 4
-3 -4 -4
2 2 3
-2 -3 -3
예시 2 · stdin
2
-0.4
0.5
stdout
0 -1 0
0 0 1
main.py
입력(stdin)

실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).

$ 준비됐어요

코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.

다른 언어로는?언어별 풀이 보기 · 8개 언어 풀이

실수를 정수로 바꾸는 방법이 세 가지이고, 이름이 비슷해 헷갈려요.
① 버림(0 쪽으로): C·C++·Java·C#의 (int)x, Python int(x), JS·TS Math.trunc(x), 크레이콘 수학.몫(x, 1).
② 내림(작은 쪽으로): Python math.floor, JS·TS·Java Math.floor, C# Math.Floor, C·C++ floor, 크레이콘 수학.내림.
양수에서는 ①과 ②가 같아서 음수에서만 틀려요 — (int)-3.7은 -3이고 내림은 -4예요.
③ 반올림은 언어마다 딱 반(.5)을 다르게 처리해요.
C·C++ round()와 크레이콘 수학.반올림은 0에서 먼 쪽(-2.5 → -3)이라 그대로 맞아요.
Python round()와 C# Math.Round()는 기본이 짝수 쪽(은행원 반올림: round(2.5) == 2, round(0.5) == 0)이라, C#은 MidpointRounding.AwayFromZero를 주고 Python은 floor(abs(x) + 0.5)에 부호를 붙여요.
JS Math.round와 Java Math.round는 위쪽(+∞)으로 가서 Math.round(-2.5)가 -2예요.
흔한 우회 floor(x + 0.5)도 음수의 반에서 같은 이유로 틀려요.
또 하나: 글자 "3.7"을 바로 정수로 바꾸면 Python int("3.7")은 ValueError, Java Integer.parseInt는 NumberFormatException이에요 — 먼저 실수로(float, Double.parseDouble) 읽어야 해요.
마지막으로 -0: JS에서 Math.sign(-0.4) * 0은 -0이고 console.log(-0)은 "-0"을 찍지만 join·String은 "0"으로 써요.
C# Math.Round(-0.4)도 double -0이라 .NET Core 3.0부터 "-0"으로 찍히니 (int)로 바꿔서 출력해요.

Pythonmain.py · 10 줄
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 줄
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 줄
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 줄
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 줄
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 줄
#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 줄
#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 줄
n = 콘솔.줄읽기().수로변환();반복 (i = 0; i < n; i++){    x = 콘솔.줄읽기().수로변환();    버림 = 수학.몫(x, 1);    내림 = 수학.내림(x);    반올림 = 수학.반올림(x);    콘솔.쓰기([버림, 내림, 반올림]);}