Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ฟังก์ชัน floor() และ ceil() ใน Python

เมธอดทั้งสองนี้เป็นส่วนหนึ่งของโมดูล math ของ Python ซึ่งช่วยให้ได้ค่าจำนวนเต็มที่ใกล้เคียงที่สุดของตัวเลขทศนิยม

floor()

ยอมรับตัวเลขที่มีทศนิยมเป็นพารามิเตอร์และคืนค่าจำนวนเต็มที่น้อยกว่าตัวเลขนั้นเอง

ไวยากรณ์

Syntax: floor(x)
โดย x เป็นค่าตัวเลข

ตัวอย่างของ floor()

ในตัวอย่างด้านล่าง เราเอาประเภทตัวเลขต่างๆ เช่น จำนวนเต็ม ทศนิยมบวก และทศนิยมลบ และใช้ฟังก์ชัน floor กับพวกมัน เราได้จำนวนเต็มที่ใกล้เคียงที่สุดซึ่งน้อยกว่าค่าตัวเลขที่ให้มา

import math
x, y, z = 21, -23.6, 14.2
print("The value of", x, "on applying floor() function is:", math.floor(x))
print("The value of", y, "on applying floor() function is:", math.floor(y))
print("The value of", z, "on applying floor() function is:", math.floor(z))

ผลลัพธ์

การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:

The value of 21 on applying floor() function is: 21
The value of -23.6 on applying floor() function is: -24
The value of 14.2 on applying floor() function is: 14

ceil()

ยอมรับตัวเลขที่มีทศนิยมเป็นพารามิเตอร์และคืนค่าจำนวนเต็มที่มากกว่าตัวเลขนั้นเอง

ไวยากรณ์

Syntax: ceil(x)
โดย x เป็นค่าตัวเลข

ตัวอย่างของ ceil()

ในตัวอย่างด้านล่าง เราเอาประเภทตัวเลขต่างๆ เช่น จำนวนเต็ม ทศนิยมบวก และทศนิยมลบ และใช้ฟังก์ชัน ceil กับพวกมัน เราได้จำนวนเต็มที่ใกล้เคียงที่สุดซึ่งมากกว่าค่าตัวเลขที่ให้มา

import math
x, y, z = 21, -23.6, 14.2
print("The value of", x, "on applying ceil() function is:", math.ceil(x))
print("The value of", y, "on applying ceil() function is:", math.ceil(y))
print("The value of", z, "on applying ceil() function is:", math.ceil(z))

ผลลัพธ์

การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:

The value of 21 on applying ceil() function is: 21
The value of -23.6 on applying ceil() function is: -23
The value of 14.2 on applying ceil() function is: 15