用例子寫一個 Python 程序來尋找矩形的面積和周長。在我們進入 Python 程序尋找矩形面積的例子之前,讓我們看看定義和公式。
矩形的 Python 面積
如果我們知道寬度和高度,我們就可以用下面的公式計算矩形的面積。
面積=寬度*高度
周長是邊緣周圍的距離。我們可以用下面的公式計算矩形的周長
周長= 2 *(寬度+高度)
尋找矩形面積和矩形周長的 Python 程序
這個矩形面積程序允許用戶輸入矩形的寬度和高度。使用這些值,這個 python 程序將計算矩形的面積和周長。
# Python Program to find Area of a Rectangle
width = float(input('Please Enter the Width of a Rectangle: '))
height = float(input('Please Enter the Height of a Rectangle: '))
# calculate the area
Area = width * height
# calculate the Perimeter
Perimeter = 2 * (width + height)
print("\n Area of a Rectangle is: %.2f" %Area)
print(" Perimeter of Rectangle is: %.2f" %Perimeter)
以下語句將允許用戶輸入矩形的寬度和高度。
width = float(input('Please Enter the Width of a Rectangle: '))
height = float(input('Please Enter the Height of a Rectangle: '))
接下來,我們按照公式 計算面積
Area = width * height
在下一條 Python 線中,我們正在計算矩形的周長
Perimeter = 2 * (width + height)
以下列印語句將幫助我們列印矩形的周長和面積
print("\n Area of a Rectangle is: %.2f" %Area)
print(" Perimeter of Rectangle is: %.2f" %Perimeter)
使用函數尋找矩形面積的 Python 程序
這個 Python 面積的矩形程序允許用戶輸入矩形的寬度和高度。我們將把這些值傳遞給函數參數來計算矩形的面積。
# Python Program to find Area of a Rectangle using Functions
def Area_of_a_Rectangle(width, height):
# calculate the area
Area = width * height
# calculate the Perimeter
Perimeter = 2 * (width + height)
print("\n Area of a Rectangle is: %.2f" %Area)
print(" Perimeter of Rectangle is: %.2f" %Perimeter)
Area_of_a_Rectangle(6, 4)
在矩形程序的這個面積內,首先,我們使用 def 關鍵字定義了帶有兩個參數的函數。這意味著,用戶將輸入矩形的寬度和高度。接下來,我們計算一個矩形的周長和面積,就像我們在第一個例子中描述的那樣。
Area of a Rectangle is: 24.00
Perimeter of Rectangle is: 20.00
>>> Area_of_a_Rectangle(12, 9)
Area of a Rectangle is: 108.00
Perimeter of Rectangle is: 42.00
>>>
原創文章,作者:VHLN5,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/127464.html