{ }codelper
四舍五入P0425

观测站的每日平均气温

某观测站连续几天测量并记录了气温。
第一行给出天数 d。
接下来 d 行每行对应一天:当天测量的次数 k,以及测得的 k 个气温,用一个空格隔开。
气温单位是摄氏度,总是写成小数点后恰好一位(例如 -3.5、0.0、12.0)。
0 总是写成 0.0,不会出现 -0.0。
对每一天,把当天 k 个气温平均值的精确值舍入到小数点后第一位。
如果要舍入的值正好位于两个一位小数的正中间,就朝远离 0 的方向舍入(0.25 → 0.3,-0.25 → -0.3,-0.65 → -0.7)。
不在正中间时,舍入到较近的一个。
按输入顺序,每行输出一天的平均气温。
最后一行输出把所有天测得的气温全部合在一起、用同样方法求出的平均值。
这个最后的值不是每天平均值的平均。
输出的数都写成小数点后恰好一位(2 写成 2.0,-0.5 写成 -0.5)。
小于 0 的值前面加 -;舍入结果为 0 时写 0.0,而不是 -0.0。

输入
1 ≤ d ≤ 1,000,1 ≤ k ≤ 100,-50.0 ≤ 气温 ≤ 50.0(小数点后恰好一位)
输出
d 行,每行是一天的平均气温;最后一行是所有气温的平均值(都保留小数点后一位)
样例 1 · stdin
3
4 -3.5 -1.0 0.5 2.0
2 -0.1 -0.4
2 1.2 1.3
stdout
-0.5
-0.3
1.3
0.0
样例 2 · stdin
2
3 -0.1 0.0 0.0
2 -2.3 1.0
stdout
0.0
-0.7
-0.3
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

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

其他语言怎么写?查看各语言题解 · 8 种语言题解

本题 8 种语言都可以作答。
所有解答都把气温换成以 0.1 度为单位的整数来处理:Python、JS、TS、Java、C#、Craykon 去掉 "-3.5" 里的小数点读成 -35,C、C++ 按浮点数读入后用 lround(x * 10) 变成整数(乘以 10 后的值非常接近整数,舍入后是精确的)。
这样,平均值就变成把整数和 s 除以 k 的结果舍入成整数。
第一个陷阱是正好一半时的方向。
本题要求远离 0(-2.5 → -3),但 Python round 和 C# 默认的 Math.Round 取偶数,于是例 1 中 1.2 和 1.3 的平均 12.5 变成 12,也就是 1.2。
Java Math.round 和 JS/TS Math.round 朝 +∞ 方向,正数没问题,但 -0.1 和 -0.4 的平均 -2.5 变成 -2,也就是 -0.2。
C lround、C++ std::lround、C# Math.Round(x, MidpointRounding.AwayFromZero)、Craykon 数学.四舍五入 都远离 0,可以直接用。
Python 用 (2 * abs(s) + k) // (2 * k) 再加上符号,只用整数计算,Java 也用同样的式子。
JS/TS 用 Math.round(Math.abs(s) / k) 再把符号加回去。
s / k 用浮点数也没关系:正好一半的值(如 -6.5)能被浮点数精确表示,不是一半的值离一半至少 1/(2k)。
第二个陷阱是用以度为单位的浮点数求平均。
例 2 第二天的 -2.3 + 1.0 在浮点数里是 -1.2999999999999998,除以 2 再乘 10 得到 -6.499…,结果是 -0.6 而不是 -0.7。
第三个陷阱是把负数写成一位小数。
t = -5(-0.5 度)时,C、C++、Java、C#、JS(Math.trunc)的 t / 10 是 0,符号丢失(直接写余数得到 0.-5,写余数的绝对值得到 0.5);Python divmod(-5, 10) 是 (-1, 5),得到 -1.5。
先写符号,再对绝对值求商和余数(Craykon 用 数学.绝对值、数学.商)。
第四个陷阱是 -0.0。
如果把舍入后的值留作浮点数,再用 "%.1f" 或 ToString("F1") 输出,例 2 第一天的 -0.0333… 舍入成 -0,在 C、Python、Java、C# 里会印出 -0.0(JS (-0).toFixed(1) 是 0.0)。
用整数处理时 0 没有符号,不会出现这个问题。
第五个陷阱是最后一行。
例 1 中每天平均值 -0.5、-0.3、1.3 的平均是 0.2,但 8 个气温全部加起来是 0,所以答案是 0.0。
要分别累计总和与个数,最后只除一次。
总和最多是 10 万个 × 500 = 5000 万,放得进 int。

Pythonmain.py · 35 行
import sys  def round_half_away(s, k):    # s / k 를 가장 가까운 정수로, 딱 반이면 0에서 먼 쪽으로(정수만 써서 정확하게)    q = (2 * abs(s) + k) // (2 * k)    return q if s >= 0 else -q  def fmt(t):    # t는 0.1도 단위 정수: -5 → "-0.5", 0 → "0.0"    sign = "-" if t < 0 else ""    a = abs(t)    return f"{sign}{a // 10}.{a % 10}"  def main():    lines = sys.stdin.read().split("\n")    d = int(lines[0])    out = []    total = 0    count = 0    for i in range(1, d + 1):        parts = lines[i].split()        k = int(parts[0])        # "-3.5" → "-35": 소수점을 지워 0.1도 단위 정수로 읽는다        s = sum(int(p.replace(".", "")) for p in parts[1:k + 1])        out.append(fmt(round_half_away(s, k)))        total += s        count += k    out.append(fmt(round_half_away(total, count)))    print("\n".join(out))  main()
JavaScriptmain.js · 33 行
const lines = require("fs").readFileSync(0, "utf8").split("\n");const d = Number(lines[0]); // s / k 를 가장 가까운 정수로, 딱 반이면 0에서 먼 쪽으로// Math.round는 딱 반을 +∞ 쪽으로 보내서(-2.5 → -2) 절댓값에 쓰고 부호를 다시 붙인다function roundHalfAway(s, k) {  const q = Math.round(Math.abs(s) / k);  return s < 0 ? -q : q;} // t는 0.1도 단위 정수: -5 → "-0.5", 0 → "0.0"function fmt(t) {  const sign = t < 0 ? "-" : "";  const a = Math.abs(t);  return `${sign}${Math.floor(a / 10)}.${a % 10}`;} const out = [];let total = 0;let count = 0;for (let i = 1; i <= d; i++) {  const parts = lines[i].trim().split(" ");  const k = Number(parts[0]);  let s = 0;  for (let j = 1; j <= k; j++) {    s += Number(parts[j].replace(".", "")); // "-3.5" → -35  }  out.push(fmt(roundHalfAway(s, k)));  total += s;  count += k;}out.push(fmt(roundHalfAway(total, count)));console.log(out.join("\n"));
TypeScriptmain.ts · 34 行
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const d: number = Number(lines[0]); // s / k 를 가장 가까운 정수로, 딱 반이면 0에서 먼 쪽으로// Math.round는 딱 반을 +∞ 쪽으로 보내서(-2.5 → -2) 절댓값에 쓰고 부호를 다시 붙인다function roundHalfAway(s: number, k: number): number {  const q = Math.round(Math.abs(s) / k);  return s < 0 ? -q : q;} // t는 0.1도 단위 정수: -5 → "-0.5", 0 → "0.0"function fmt(t: number): string {  const sign = t < 0 ? "-" : "";  const a = Math.abs(t);  return `${sign}${Math.floor(a / 10)}.${a % 10}`;} const out: string[] = [];let total = 0;let count = 0;for (let i = 1; i <= d; i++) {  const parts: string[] = lines[i].trim().split(" ");  const k = Number(parts[0]);  let s = 0;  for (let j = 1; j <= k; j++) {    s += Number(parts[j].replace(".", "")); // "-3.5" → -35  }  out.push(fmt(roundHalfAway(s, k)));  total += s;  count += k;}out.push(fmt(roundHalfAway(total, count)));console.log(out.join("\n"));
JavaMain.java · 40 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class Main {    // s / k 를 가장 가까운 정수로, 딱 반이면 0에서 먼 쪽으로(정수만 써서 정확하게)    // Math.round는 딱 반을 +∞ 쪽으로 보내서(-2.5 → -2) 쓰지 않는다    static long roundHalfAway(long s, long k) {        long q = (2 * Math.abs(s) + k) / (2 * k);        return s < 0 ? -q : q;    }     // t는 0.1도 단위 정수: -5 → "-0.5", 0 → "0.0"    static String fmt(long t) {        String sign = t < 0 ? "-" : "";        long a = Math.abs(t);        return sign + (a / 10) + "." + (a % 10);    }     public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        int d = Integer.parseInt(br.readLine().trim());        StringBuilder sb = new StringBuilder();        long total = 0;        long count = 0;        for (int i = 0; i < d; i++) {            String[] parts = br.readLine().trim().split(" ");            int k = Integer.parseInt(parts[0]);            long s = 0;            for (int j = 1; j <= k; j++) {                s += Integer.parseInt(parts[j].replace(".", "")); // "-3.5" → -35            }            sb.append(fmt(roundHalfAway(s, k))).append('\n');            total += s;            count += k;        }        sb.append(fmt(roundHalfAway(total, count))).append('\n');        System.out.print(sb);    }}
C#Main.cs · 43 行
using System;using System.Text; class Program{    // s / k 를 가장 가까운 정수로, 딱 반이면 0에서 먼 쪽으로    // Math.Round의 기본은 짝수 쪽이라 AwayFromZero를 준다    static long RoundHalfAway(long s, long k)    {        return (long)Math.Round((double)s / k, MidpointRounding.AwayFromZero);    }     // t는 0.1도 단위 정수: -5 → "-0.5", 0 → "0.0"    static string Fmt(long t)    {        string sign = t < 0 ? "-" : "";        long a = Math.Abs(t);        return sign + (a / 10) + "." + (a % 10);    }     static void Main()    {        int d = int.Parse(Console.ReadLine().Trim());        var sb = new StringBuilder();        long total = 0;        long count = 0;        for (int i = 0; i < d; i++)        {            string[] parts = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);            int k = int.Parse(parts[0]);            long s = 0;            for (int j = 1; j <= k; j++)            {                s += int.Parse(parts[j].Replace(".", "")); // "-3.5" → -35            }            sb.Append(Fmt(RoundHalfAway(s, k))).Append('\n');            total += s;            count += k;        }        sb.Append(Fmt(RoundHalfAway(total, count))).Append('\n');        Console.Write(sb);    }}
C++main.cpp · 40 行
#include <cmath>#include <cstdio>#include <cstdlib>#include <iostream>#include <string> // s / k 를 가장 가까운 정수로, 딱 반이면 0에서 먼 쪽으로: std::lround가 바로 그 규칙이다long roundHalfAway(long s, long k) {    return std::lround(static_cast<double>(s) / k);} // t는 0.1도 단위 정수: -5 → "-0.5", 0 → "0.0"std::string fmt(long t) {    long a = std::labs(t);    return std::string(t < 0 ? "-" : "") + std::to_string(a / 10) + "." + std::to_string(a % 10);} int main() {    // 수가 10만 개까지라 scanf로 읽는다(macOS의 libc++ cin은 실수를 읽는 데 이 크기에서 0.5초쯤 걸린다)    int d;    if (std::scanf("%d", &d) != 1) return 0;    std::string out;    long total = 0, count = 0;    for (int i = 0; i < d; i++) {        int k;        std::scanf("%d", &k);        long s = 0;        for (int j = 0; j < k; j++) {            double x;            std::scanf("%lf", &x);            s += std::lround(x * 10);  // -3.5 → -35: 10을 곱한 값은 정수에 아주 가까우니 반올림해 정수로        }        out += fmt(roundHalfAway(s, k)) + "\n";        total += s;        count += k;    }    out += fmt(roundHalfAway(total, count)) + "\n";    std::cout << out;    return 0;}
Cmain.c · 35 行
#include <math.h>#include <stdio.h>#include <stdlib.h> /* s / k 를 가장 가까운 정수로, 딱 반이면 0에서 먼 쪽으로: lround가 바로 그 규칙이다 */long round_half_away(long s, long k) {    return lround((double)s / k);} /* t는 0.1도 단위 정수: -5 → "-0.5", 0 → "0.0" */void print_tenths(long t) {    long a = labs(t);    printf("%s%ld.%ld\n", t < 0 ? "-" : "", a / 10, a % 10);} int main(void) {    int d;    if (scanf("%d", &d) != 1) return 0;    long total = 0, count = 0;    for (int i = 0; i < d; i++) {        int k;        scanf("%d", &k);        long s = 0;        for (int j = 0; j < k; j++) {            double x;            scanf("%lf", &x);            s += lround(x * 10); /* -3.5 → -35: 10을 곱한 값은 정수에 아주 가까우니 반올림해 정수로 */        }        print_tenths(round_half_away(s, k));        total += s;        count += k;    }    print_tenths(round_half_away(total, count));    return 0;}
Craykonmain.cray · 30 行
// t는 0.1도 단위 정수: -5 → "-0.5", 0 → "0.0"표시(t){    부호 = "";    如果 (t < 0)    {        부호 = "-";    }    a = 数学.绝对值(t);    返回 부호 + 数学.商(a, 10) + "." + a % 10;} d = 控制台.读行().转数字();total = 0;count = 0;循环 (i = 0; i < d; i++){    parts = 控制台.读行().去空白().分割(" ");    k = parts[0].转数字();    s = 0;    循环 (j = 1; j <= k; j++)    {        s = s + parts[j].替换(".", "").转数字(); // "-3.5" → -35    }    // 수학.반올림은 딱 반을 0에서 먼 쪽으로 보낸다(-2.5 → -3)    控制台.输出(표시(数学.四舍五入(s / k)));    total = total + s;    count = count + k;}控制台.输出(표시(数学.四舍五入(total / count)));