{ }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.7 ではなく -0.6 になります。
三つ目の落とし穴は、負の数を小数一桁で書くことです。
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)));