{ }codelper
平均小数の割り算小数の出力P0014

平均を小数第二位まで

一行目に点数の個数 n、二行目に整数の点数 n 個が与えられる。
点数の平均を小数第三位で四捨五入して(第三位が 5 以上なら切り上げ)小数第二位まで出力せよ。
平均が整数でも小数二桁を書く(85 → 85.00)。
例:平均が 0.125 なら 0.13、0.145 なら 0.15、1.005 なら 1.01。

入力
1 ≤ n ≤ 1,000、0 ≤ 点数 ≤ 100
出力
平均を一行、小数点以下ちょうど二桁
例 1 · stdin
3
70 85 90
stdout
81.67
例 2 · stdin
8
1 0 0 0 0 0 0 0
stdout
0.13
main.py
入力(stdin)

実行すると、これらの行が順に input()・標準入力に渡されます(実行中に入力を求めません)。

$ 準備完了

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

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

落とし穴は二重です。
① 整数の割り算:C・C++・Java・C# の total / n は int 同士なので小数が先に切り捨てられます — (double) total / n や total * 100.0 / n のように片方を実数に。
Python 3 の /、JS・TS・Craykon の / はもともと小数まで割ります。
② 四捨五入:実数は二進数なので 0.145 は実際には 0.14499… です。
平均にそのまま書式を使うと言語ごとに答えが変わります — Python f"{x:.2f}"、C・C++ printf("%.2f")・std::setprecision(2)、C# ToString("F2") は実際の値で丸め、ちょうど半分なら偶数側(0.125 → 0.12、0.145 → 0.14)、JS・TS toFixed(2) は 0.125 → 0.13 でも 0.145 → 0.14。
Java String.format("%.2f") は短い十進表記を HALF_UP で丸めるのでそのままで正しく(0.15)、Craykon 文字.桁そろえ(x, 2) も 5 を切り上げるのでそのままで正しいです。
ほかは 100 倍した平均 total * 100 / n を丸めます — ちょうど半分ならこの値は 12.5 のように正確に表せます。
それでも Python round() と C# Math.Round() は既定が偶数丸め(round(12.5) == 12)なので、Python は math.floor(x + 0.5)、C# は MidpointRounding.AwayFromZero、C・C++ は round()、JS・TS は Math.round() を使います。

Pythonmain.py · 7 行
import math n = int(input())total = sum(map(int, input().split()))# 100배 한 평균을 반올림(5는 올림). round()는 0.5를 짝수 쪽으로 보내서 쓰지 않는다cents = math.floor(total * 100 / n + 0.5)print(f"{cents / 100:.2f}")
JavaScriptmain.js · 5 行
const [n, ...a] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const total = a.reduce((s, x) => s + x, 0);// 100배 한 평균을 반올림한 뒤 다시 나눈다 — toFixed를 평균에 바로 쓰면 0.145가 0.14가 된다const cents = Math.round((total * 100) / n);console.log((cents / 100).toFixed(2));
TypeScriptmain.ts · 5 行
import { readFileSync } from "node:fs";const [n, ...a]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const total: number = a.reduce((s, x) => s + x, 0);const cents: number = Math.round((total * 100) / n);console.log((cents / 100).toFixed(2));
JavaMain.java · 16 行
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Locale; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(br.readLine().trim());        int total = 0;        for (String s : br.readLine().trim().split("\\s+")) total += Integer.parseInt(s);        // (double)로 바꾸지 않으면 total / n이 정수 나눗셈이 된다        double avg = (double) total / n;        // Java의 %.2f는 반올림(HALF_UP)이다. Locale.ROOT로 소수점을 늘 '.'로        System.out.println(String.format(Locale.ROOT, "%.2f", avg));    }}
C#Main.cs · 15 行
using System;using System.Globalization;using System.Linq; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine().Trim());        int total = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Sum(int.Parse);        // 100배 한 평균을 0에서 먼 쪽으로 반올림(Math.Round의 기본은 짝수 쪽)        double cents = Math.Round(total * 100.0 / n, MidpointRounding.AwayFromZero);        Console.WriteLine((cents / 100).ToString("F2", CultureInfo.InvariantCulture));    }}
C++main.cpp · 14 行
#include <cmath>#include <iomanip>#include <iostream> int main() {    int n, x, total = 0;    std::cin >> n;    for (int i = 0; i < n; i++) {        std::cin >> x;        total += x;    }    double cents = std::round(total * 100.0 / n);    std::cout << std::fixed << std::setprecision(2) << cents / 100 << '\n';}
Cmain.c · 15 行
#include <math.h>#include <stdio.h> int main(void) {    int n, x, total = 0;    scanf("%d", &n);    for (int i = 0; i < n; i++) {        scanf("%d", &x);        total += x;    }    /* 100.0을 곱해야 실수 나눗셈이 된다. round()는 0.5를 0에서 먼 쪽으로 올린다 */    double cents = round(total * 100.0 / n);    printf("%.2f\n", cents / 100);    return 0;}
Craykonmain.cray · 9 行
n = コンソール.行読み().数に();점수들 = コンソール.数読み();합 = 0;それぞれ (x の中 점수들){    합 += x;}// / 는 늘 소수까지 나눈다. 자리맞추기는 5를 올리는 반올림이다コンソール.書く(文字.桁そろえ(합 / n, 2));