logo

Python の Floor() および ceil() 関数

Floor() 関数:

Python の Floor() メソッドは、x のフロア、つまり x 以下の最大の整数を返します。

 Syntax: import math math.floor(x) Parameter:  x-numeric expression. Returns:  largest integer not greater than x.>

以下は、floor() メソッドの Python 実装です。



パイソン






# Python program to demonstrate the use of floor() method> # This will import math module> import> math> # prints the ceil using floor() method> print> 'math.floor(-23.11) : '>, math.floor(>->23.11>)> print> 'math.floor(300.16) : '>, math.floor(>300.16>)> print> 'math.floor(300.72) : '>, math.floor(>300.72>)>



>

>

bashの部分文字列

出力:

math.floor(-23.11) : -24.0 math.floor(300.16) : 300.0 math.floor(300.72) : 300.0>

ceil() 関数:

Python のメソッド ceil(x) は、x の上限値、つまり x 以上の最小の整数を返します。

 Syntax:  import math math.ceil(x) Parameter: x:This is a numeric expression. Returns:  Smallest integer not less than x.>

以下は ceil() メソッドの Python 実装です。

パイソン




# Python program to demonstrate the use of ceil() method> # This will import math module> import> math> # prints the ceil using ceil() method> print> 'math.ceil(-23.11) : '>, math.ceil(>->23.11>)> print> 'math.ceil(300.16) : '>, math.ceil(>300.16>)> print> 'math.ceil(300.72) : '>, math.ceil(>300.72>)>

>

>

出力:

math.ceil(-23.11) : -23.0 math.ceil(300.16) : 301.0 math.ceil(300.72) : 301.0>

整数の除算と加算を使用する:

このアプローチでは、x // 1 を使用して x の整数部分を取得します。これは math.floor(x) と同等です。 x の上限を取得するには、x の整数部分に 1 を加えます。

Python3




x>=> 4.5> # Round x down to the nearest integer> rounded_down>=> x>/>/> 1> print>(rounded_down)># Output: 4> # Round x up to the nearest integer> rounded_up>=> x>/>/> 1> +> 1> print>(rounded_up)># Output: 5>

>

>

COBOLプログラミング
出力

4.0 5.0>

アプローチ:
このコードは浮動小数点数 x を受け取り、floor 除算を使用して最も近い整数に切り捨てます。次に、結果を出力します。次に、フロア除算と加算を使用して x を最も近い整数に切り上げ、結果を出力します。

時間計算量:
Round() 関数の時間計算量は一定です。これは、代替コードの時間計算量も一定であることを意味します。元のコードでは単純な算術演算がいくつかしか使用されていないため、元のコードの時間計算量も一定です。

空間の複雑さ:
元のコードと代替コードはどちらも入力と結果を格納するために少数の変数しか使用しないため、空間複雑度は一定です。