{ }codelper
小数の割り算多分岐P0420

自転車道の勾配案内板

自転車道の区間ごとに勾配の案内板を立てる。
最初の行に区間の数 n が与えられる。
続く n 行には、区間ごとに上る高さ h と水平距離 d が空白一つで区切って与えられる。
h と d はどちらもセンチメートル単位の整数である。
区間の勾配 s は、h × 100 を d で割った値を正確に計算したものである(単位は %)。
s が 3 以下なら "平坦"、3 より大きく 7 以下なら "ゆるやか"、7 より大きく 14 以下なら "急"、14 より大きければ "押して歩く" を出力する。
境界の値は下の段階に入る(s がちょうど 7 なら "ゆるやか"、ちょうど 14 なら "急")。
区間ごとに入力の順に、一行に一つずつ案内板の言葉を出力せよ。
最後の行には、s が最も大きい区間の番号を出力する。
区間の番号は入力の順に 1 から数える。
s が最も大きい区間が複数あれば、その中で最も小さい番号を出力する。

入力
1 ≤ n ≤ 1,000、1 ≤ d ≤ 100,000、0 ≤ h ≤ d(すべて整数)
出力
n 行:区間ごとに flat、gentle、steep、walk のいずれか。
最後の行:s が最も大きい区間の番号
例 1 · stdin
5
3 100
7 100
15 200
14 100
29 200
stdout
平坦
ゆるやか
急
急
押して歩く
5
例 2 · stdin
3
7 50
0 10
28 200
stdout
急
平坦
急
1
main.py
入力(stdin)

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

$ 準備完了

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

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

この問題は 8 言語すべてを受け付けます。
勾配の式は同じですが、計算の順番と割り算の演算子によって境界で答えが分かれます。
落とし穴その一:割ってから 100 を掛ける順番です。
h / d * 100 は 7 100 でまず 7 / 100 = 0.07 を作ります。
0.07 は 2 進数でぴったり表せないので最も近い double に入り、100 を掛けると 7.000000000000001 になって 7 より大きくなります。
そのため例の 7 100 が "steep"、14 100 が "walk" と出ます(14 / 100 * 100 = 14.000000000000002、7 / 50 * 100 も 14.000000000000002)。
8 言語はすべて同じ IEEE 754 の double で計算するので、Python・JS・TS・Java・C#・C・C++・Craykon で同じように誤ります。
先に 100 を掛ける h * 100 / d なら、h × 100 も d も正確な整数で、一回の割り算は真の値に最も近い double を返すので、真の値が 7 ならちょうど 7.0 になります。
なお h / d <= 0.07 のように割った値をそのまま 0.07 と比べるのも正しいです。
h / d と 0.07 はどちらも 7/100 に最も近い同じ double だからです。
実数をまったく使わないなら、h * 100 <= 7 * d のように整数どうしを掛けて比べてもかまいません(最大でも 10,000,000 で 32 ビットの int に収まります)。
落とし穴その二:整数の割り算です。
C・C++・Java・C# では int どうしの h * 100 / d は商だけを残すので、例の 15 200(7.5%)が 7 になり "gentle" と出ます。
h * 100.0 / d や (double) h * 100 / d のように、割る前に実数に変えます。
Python の / は整数どうしでも小数まで割りますが、// と書くと同じく 7 になります。
JS・TS と Craykon の / はいつも小数まで割り、Craykon で商だけが欲しいときは 数学.商 を使います。
落とし穴その三:境界の値は下の段階です。
< と書くと例の 3 100 が "gentle"、7 100 が "steep" になります。
落とし穴その四:最も急な区間が複数あれば前の番号です。
比較を >= にすると後ろの区間に変わり、例 2 で 1 ではなく 3 と出ます。
いくつにも分かれる条件は Python elif、JS・TS・Java・C#・C・C++ else if、Craykon でなければ もし と書きます。
JS・TS の解答は条件演算子 ? : をつないでいます。

Pythonmain.py · 17 行
n = int(input())best, best_slope = 1, -1.0for i in range(1, n + 1):    h, d = map(int, input().split())    # 100을 먼저 곱하고 나눈다: h / d * 100은 7 / 100 * 100 = 7.000000000000001이 된다    slope = h * 100 / d    if slope <= 3:        print("平坦")    elif slope <= 7:        print("ゆるやか")    elif slope <= 14:        print("急")    else:        print("押して歩く")    if slope > best_slope:  # 같으면 앞 구간을 그대로 둔다        best, best_slope = i, slopeprint(best)
JavaScriptmain.js · 19 行
const [n, ...v] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const sign = (slope) => (slope <= 3 ? "平坦" : slope <= 7 ? "ゆるやか" : slope <= 14 ? "急" : "押して歩く");const out = [];let best = 1;let bestSlope = -1;for (let i = 1; i <= n; i++) {  const h = v[2 * i - 2];  const d = v[2 * i - 1];  // 100을 먼저 곱하고 나눈다: h / d * 100은 7 / 100 * 100 = 7.000000000000001이 된다  const slope = (h * 100) / d;  out.push(sign(slope));  if (slope > bestSlope) {    // 같으면 앞 구간을 그대로 둔다    best = i;    bestSlope = slope;  }}out.push(String(best));console.log(out.join("\n"));
TypeScriptmain.ts · 21 行
import { readFileSync } from "node:fs";const [n, ...v]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const sign = (slope: number): string =>  slope <= 3 ? "平坦" : slope <= 7 ? "ゆるやか" : slope <= 14 ? "急" : "押して歩く";const out: string[] = [];let best: number = 1;let bestSlope: number = -1;for (let i = 1; i <= n; i++) {  const h: number = v[2 * i - 2];  const d: number = v[2 * i - 1];  // 100을 먼저 곱하고 나눈다: h / d * 100은 7 / 100 * 100 = 7.000000000000001이 된다  const slope: number = (h * 100) / d;  out.push(sign(slope));  if (slope > bestSlope) {    // 같으면 앞 구간을 그대로 둔다    best = i;    bestSlope = slope;  }}out.push(String(best));console.log(out.join("\n"));
JavaMain.java · 36 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.StringTokenizer; public class Main {    static String sign(double slope) {        if (slope <= 3) return "平坦";        if (slope <= 7) return "ゆるやか";        if (slope <= 14) return "急";        return "押して歩く";    }     public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(br.readLine().trim());        StringBuilder out = new StringBuilder();        int best = 1;        double bestSlope = -1;        for (int i = 1; i <= n; i++) {            StringTokenizer st = new StringTokenizer(br.readLine());            int h = Integer.parseInt(st.nextToken());            int d = Integer.parseInt(st.nextToken());            // int끼리 나누면 몫만 남으므로 double로 바꾼 뒤 나눈다.            // 100을 먼저 곱한다: h / d * 100은 7 / 100 * 100 = 7.000000000000001이 된다            double slope = h * 100.0 / d;            out.append(sign(slope)).append('\n');            if (slope > bestSlope) { // 같으면 앞 구간을 그대로 둔다                best = i;                bestSlope = slope;            }        }        out.append(best).append('\n');        System.out.print(out);    }}
C#Main.cs · 38 行
using System;using System.Text; class Program{    static string Sign(double slope)    {        if (slope <= 3) return "平坦";        if (slope <= 7) return "ゆるやか";        if (slope <= 14) return "急";        return "押して歩く";    }     static void Main()    {        int n = int.Parse(Console.ReadLine());        var out_ = new StringBuilder();        int best = 1;        double bestSlope = -1;        for (int i = 1; i <= n; i++)        {            string[] p = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);            int h = int.Parse(p[0]);            int d = int.Parse(p[1]);            // int끼리 나누면 몫만 남으므로 double로 바꾼 뒤 나눈다.            // 100을 먼저 곱한다: h / d * 100은 7 / 100 * 100 = 7.000000000000001이 된다            double slope = h * 100.0 / d;            out_.Append(Sign(slope)).Append('\n');            if (slope > bestSlope) // 같으면 앞 구간을 그대로 둔다            {                best = i;                bestSlope = slope;            }        }        out_.Append(best).Append('\n');        Console.Write(out_);    }}
C++main.cpp · 30 行
#include <iostream>#include <string> std::string sign(double slope) {    if (slope <= 3) return "平坦";    if (slope <= 7) return "ゆるやか";    if (slope <= 14) return "急";    return "押して歩く";} int main() {    std::ios::sync_with_stdio(false);    int n;    std::cin >> n;    int best = 1;    double bestSlope = -1;    for (int i = 1; i <= n; i++) {        int h, d;        std::cin >> h >> d;        // int끼리 나누면 몫만 남으므로 double로 바꾼 뒤 나눈다.        // 100을 먼저 곱한다: h / d * 100은 7 / 100 * 100 = 7.000000000000001이 된다        double slope = h * 100.0 / d;        std::cout << sign(slope) << '\n';        if (slope > bestSlope) {  // 같으면 앞 구간을 그대로 둔다            best = i;            bestSlope = slope;        }    }    std::cout << best << '\n';}
Cmain.c · 30 行
#include <stdio.h> int main(void) {    int n;    scanf("%d", &n);    int best = 1;    double best_slope = -1;    for (int i = 1; i <= n; i++) {        int h, d;        scanf("%d %d", &h, &d);        /* int끼리 나누면 몫만 남으므로 double로 바꾼 뒤 나눈다.           100을 먼저 곱한다: h / d * 100은 7 / 100 * 100 = 7.000000000000001이 된다 */        double slope = h * 100.0 / d;        if (slope <= 3) {            puts("平坦");        } else if (slope <= 7) {            puts("ゆるやか");        } else if (slope <= 14) {            puts("急");        } else {            puts("押して歩く");        }        if (slope > best_slope) { /* 같으면 앞 구간을 그대로 둔다 */            best = i;            best_slope = slope;        }    }    printf("%d\n", best);    return 0;}
Craykonmain.cray · 34 行
n = コンソール.行読み().数に();가장 = 1;가장경사 = -1;繰り返す (i = 1; i <= n; i++){    구간 = コンソール.数読み();    h = 구간[0];    d = 구간[1];    // 100을 먼저 곱하고 나눈다: h / d * 100은 7 / 100 * 100 = 7.000000000000001이 된다    경사 = h * 100 / d;    もし (경사 <= 3)    {        コンソール.書く("平坦");    }    でなければ もし (경사 <= 7)    {        コンソール.書く("ゆるやか");    }    でなければ もし (경사 <= 14)    {        コンソール.書く("急");    }    でなければ    {        コンソール.書く("押して歩く");    }    // 같으면 앞 구간을 그대로 둔다    もし (경사 > 가장경사)    {        가장 = i;        가장경사 = 경사;    }}コンソール.書く(가장);