{ }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()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 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);    控制台.输出([버림, 내림, 반올림]);}