割り算の切り上げを計算する (C++)
C++
Published: 2020-01-13

やったこと

割り算した結果、小数を切り上げます。

確認環境

$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

調査

test.cpp

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main() {
    // 9 / 2 の切り上げ
    int t1 = ceil(9 / 2.0);
    cout << t1 << endl;

    // 9 / 2 の切り上げ
    int t2 = (9 + 2 - 1) / 2;
    cout << t2 << endl;


    // 9 / 3 の切り上げ
    int t3 = (9 + 3 - 1) / 3;
    cout << t3 << endl;
}

出力結果

5
5
3

2つ目の式の形

(x + y - 1) / y

こうすると割り切れる場合も、割り切れない場合も切り上げることができます。