1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#での整数の除算時にFloor・Ceilした値を返す (正値の範囲版)

Last updated at Posted at 2023-02-25

まとめ

正値の範囲において、整数の除算を行った結果をFloor・Ceilしたい時、

  • Floorは、c = a / b
  • Ceilは、c = (a - 1) / b + 1

で、計算可能。

整数の除算時にFloor (正値の範囲版)

C#で、「整数 / 整数」の除算の計算では、どのような値が算出されるかを、下記のコードで確認すると、

(int: 10→1までをint: 3で割った時。c = a / b;の部分の計算)

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            /* 結果: 
▼整数除算の「/」の確認用 Floorの値と同じ 正値の範囲のみ
int: 10 / 3 =  3
int:  9 / 3 =  3
int:  8 / 3 =  2
int:  7 / 3 =  2
int:  6 / 3 =  2
int:  5 / 3 =  1
int:  4 / 3 =  1
int:  3 / 3 =  1
int:  2 / 3 =  0
int:  1 / 3 =  0
            */

            Action<string> WL = Console.WriteLine; // 短縮

            WL("▼整数除算の「/」の確認用 Floorの値と同じ 正値の範囲のみ");
            var a = 10;
            var b = 3;
            for (; a >= 1; a--) {
                var c = a / b;
                WL($"int: {a,2} / {b} = {c,2}");
            }
        }
    }
}

Floorした値と同じものになっており、「整数 / 整数」の除算の計算は、そのままFloorした値として、使用できるものと分かります。

整数の除算時にCeil (正値の範囲版)

整数の除算を行った結果をCeilしたい時は、Floorの結果を下に2つだけシフトさせればCeilになるので、c = a / bを少しシフトさせて、c = (a - 1) / b + 1とすると、

(int: 10→1までをint: 3で割った時。c = (a - 1) / b + 1;の部分の計算)

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            /* 結果: 
▼整数除算でCeilの値を作る 正値の範囲のみ
int: 10 / 3 =  4
int:  9 / 3 =  3
int:  8 / 3 =  3
int:  7 / 3 =  3
int:  6 / 3 =  2
int:  5 / 3 =  2
int:  4 / 3 =  2
int:  3 / 3 =  1
int:  2 / 3 =  1
int:  1 / 3 =  1
            */

            Action<string> WL = Console.WriteLine; // 短縮

            WL("▼整数除算でCeilの値を作る 正値の範囲のみ");
            var a = 10;
            var b = 3;
            for (; a >= 1; a--) {
                var c = (a - 1) / b + 1;
                WL($"int: {a,2} / {b} = {c,2}");
            }
        }
    }
}

Ceilした値と同じものになります。

正値の範囲に限定した内容

「整数 / 整数」の除算は、負値の場合が特殊なので、本稿は、正値の範囲に限定した内容になっています。

詳細:

整数の除算「整数 / 整数」は、ゼロ側の整数へ寄せる動作になる (正負の間で特性が変わり特殊)
https://qiita.com/dl_from_scratch/items/b55ec179729a0e215a7a

C#での整数の除算時にFloor・Ceilした値を返す (正値・負値全ての範囲版)
https://qiita.com/dl_from_scratch/items/d3a20eaec07c3eb2c596

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?