{ }codelper
型変換n行の読み込みP0044

切り捨て・床・四捨五入

一行目に数の個数 n が与えられ、続く n 行に実数 x が一行に一つずつ与えられる。
x は整数か、小数点以下一、二桁までの数である(例:7、-3.7、0.50)。
各 x について、三つの整数を空白一つで区切って一行に出力せよ。
① 切り捨て:小数部分を取り除いた値(0 の方へ、-3.7 → -3)。
② 床(floor):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()・標準入力に渡されます(実行中に入力を求めません)。

$ 準備完了

コードを入力して解くにはパソコンで開いてください。モバイルでは問題と解答を見られます。

ほかの言語では?言語別の解答を見る · 8 言語の解答

実数を整数にする方法は三つあり、名前が似ていて混同しやすいです。
① 切り捨て(0 の方へ):C・C++・Java・C# の (int)x、Python int(x)、JS・TS Math.trunc(x)、Craykon 数学.商(x, 1)。
② 床(小さい方へ):Python math.floor、JS・TS・Java Math.floor、C# Math.Floor、C・C++ floor、Craykon 数学.切り捨て。
正の数では①と②が同じなので、負の数でだけ間違えます — (int)-3.7 は -3 で、床は -4 です。
③ 四捨五入はちょうど半分(.5)の扱いが言語ごとに違います。
C・C++ round() と Craykon 数学.四捨五入 は 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);    コンソール.書く([버림, 내림, 반올림]);}