{ }codelper
roundingP0425

Daily mean temperature at a weather station

A weather station measured the temperature over several days.
The first line gives the number of days d.
Each of the next d lines describes one day: the number of measurements k followed by the k measured temperatures, separated by single spaces.
Temperatures are in degrees Celsius and are always written with exactly one digit after the decimal point (for example -3.5, 0.0, 12.0).
Zero is always written as 0.0; -0.0 never appears.
For each day, take the exact average of that day's k temperatures and round it to one decimal place.
If the value lies exactly halfway between two one-decimal numbers, round away from zero (0.25 → 0.3, -0.25 → -0.3, -0.65 → -0.7).
Otherwise round to the nearer one.
Print each day's average temperature, one per line, in input order.
On the last line, print the average of all temperatures measured on all days together, computed the same way.
This last value is not the average of the daily averages.
Write every printed number with exactly one digit after the decimal point (2 as 2.0, -0.5 as -0.5).
Put - in front of a value below zero, and if the rounded result is zero, write 0.0, not -0.0.

Input
1 ≤ d ≤ 1,000, 1 ≤ k ≤ 100, -50.0 ≤ temperature ≤ 50.0 (exactly one digit after the decimal point)
Output
d lines with each day's average temperature, then a last line with the average of all temperatures (all with one digit after the decimal point)
Example 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
Example 2 · stdin
2
3 -0.1 0.0 0.0
2 -2.3 1.0
stdout
0.0
-0.7
-0.3
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

This problem takes all 8 languages.
Every solution turns temperatures into integers in tenths of a degree: Python, JS, TS, Java, C# and Craykon remove the decimal point from "-3.5" and read -35, while C and C++ read a double and make it an integer with lround(x * 10) (ten times the value is extremely close to an integer, so rounding it is exact).
The average then becomes rounding the integer sum s divided by k to an integer.
Trap one is the direction of exact halves.
This task goes away from zero (-2.5 → -3), but Python round and C#'s default Math.Round go to the even side, so in example 1 the average of 1.2 and 1.3, 12.5 tenths, becomes 12, i.e. 1.2.
Java Math.round and JS/TS Math.round go toward +∞, which is right for positives, but the average of -0.1 and -0.4, -2.5 tenths, becomes -2, i.e. -0.2.
C lround, C++ std::lround, C# Math.Round(x, MidpointRounding.AwayFromZero) and Craykon Mathf.Round go away from zero, so use them as they are.
Python computes (2 * abs(s) + k) // (2 * k) with integers only and puts the sign back, and Java uses the same formula.
JS/TS take Math.round(Math.abs(s) / k) and put the sign back.
s / k may be a double: exact halves (like -6.5) are represented exactly, and values that are not halves are at least 1/(2k) away from one.
Trap two is averaging floating-point degrees.
On the second day of example 2, -2.3 + 1.0 is -1.2999999999999998 in floating point, so dividing by 2 and multiplying by 10 gives -6.499…, which prints -0.6 instead of -0.7.
Trap three is writing a negative number with one decimal.
For t = -5 (-0.5 degrees), t / 10 in C, C++, Java, C# and JS (with Math.trunc) is 0, so the sign disappears (printing the remainder as is gives 0.-5, its absolute value gives 0.5); Python divmod(-5, 10) is (-1, 5), giving -1.5.
Write the sign first and take the quotient and remainder of the absolute value (in Craykon, Mathf.Abs and Mathf.Quot).
Trap four is -0.0.
If you keep the rounded value as a double and print it with "%.1f" or ToString("F1"), the first day of example 2, -0.0333…, rounds to -0, which C, Python, Java and C# print as -0.0 (JS (-0).toFixed(1) gives 0.0).
With integers, zero has no sign, so this cannot happen.
Trap five is the last line.
In example 1 the average of the daily averages -0.5, -0.3 and 1.3 is 0.2, but the sum of all 8 temperatures is 0, so the answer is 0.0.
Collect the sum and the count separately and divide once at the end.
The sum is at most 100,000 × 500 = 50 million, so it fits in an int.

Pythonmain.py · 35 lines
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 lines
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 lines
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 lines
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 lines
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 lines
#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 lines
#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 lines
// t는 0.1도 단위 정수: -5 → "-0.5", 0 → "0.0"표시(t){    부호 = "";    if (t < 0)    {        부호 = "-";    }    a = Mathf.Abs(t);    return 부호 + Mathf.Quot(a, 10) + "." + a % 10;} d = Console.ReadLine().ToNumber();total = 0;count = 0;for (i = 0; i < d; i++){    parts = Console.ReadLine().Trim().Split(" ");    k = parts[0].ToNumber();    s = 0;    for (j = 1; j <= k; j++)    {        s = s + parts[j].Replace(".", "").ToNumber(); // "-3.5" → -35    }    // 수학.반올림은 딱 반을 0에서 먼 쪽으로 보낸다(-2.5 → -3)    Console.WriteLine(표시(Mathf.Round(s / k)));    total = total + s;    count = count + k;}Console.WriteLine(표시(Mathf.Round(total / count)));