Swift 程式:計算矩形的面積
本教程將討論如何編寫一個 Swift 程式來計算矩形的面積。
矩形是一種四邊形,或是一個具有四條邊的封閉二維圖形。矩形的所有角都相等(90 度),並且相對的邊彼此相等且平行。

矩形的面積是指矩形邊界內包含的總空間。我們可以透過將矩形的長和寬相乘來計算其面積。
矩形面積公式
以下是矩形面積的公式:
Area = Length(L) * Width(W)
以下是該公式的演示:
輸入
假設我們的給定輸入是:
Length = 10 Width = 5
輸出
期望的輸出將是:
Area = 10 * 5 = 50. Area = 50
演算法
以下是演算法:
步驟 1 - 宣告兩個整型變數來儲存矩形的長和寬的值。這裡這些變數的值可以是預定義的或使用者定義的。
步驟 2 - 宣告一個 Area 變數來儲存矩形的面積。
var RectArea = RectLength * RectWidth
步驟 3 - 列印輸出。
示例 1
以下程式展示瞭如何計算矩形的面積。
import Foundation import Glibc var RectLength : Int = 20 var RectWidth : Int = 10 var RectArea = RectLength * RectWidth print("Length - ", RectLength) print("Width - ", RectWidth) print("So, Area of the rectangle- ", RectArea)
輸出
Length - 20 Width - 10 So, Area of the rectangle- 200
在上面的程式碼中,我們透過將給定的矩形的長和寬相乘來計算矩形的面積。
var RectArea = RectLength * RectWidth
即 ReactArea = 20 * 10 = 200。並顯示面積,即 200
示例 2
以下程式展示瞭如何使用使用者定義的輸入來計算矩形的面積。
import Foundation import Glibc // Taking input from the user print("Please enter the length - ") var RectLength = Int(readLine()!)! print("Please enter the width - ") var RectWidth = Int(readLine()!)! // Finding the area of the rectangle var RectArea = RectLength * RectWidth print("Entered Length - ", RectLength) print("Entered Width - ", RectWidth) print("So, Area of the rectangle- ", RectArea)
標準輸入
Please enter the length - 6 Please enter the width - 3
輸出
Entered Length - 6 Entered Width - 3 So, Area of the rectangle - 18
在上面的程式碼中,我們透過將給定的矩形的長和寬相乘來計算矩形的面積。
var RectArea = RectLength * RectW idth
這裡我們使用 readLine() 函式從使用者處獲取 RectLength 和 RectWidth 的值,並使用 Int() 函式將輸入的值轉換為整型。因此 ReactArea = 6 * 3 = 18,並顯示結果,即 18。
根據對角線計算矩形的面積
我們還可以藉助對角線和寬來計算矩形的面積。矩形有兩個對角線,並且它們都相等。
使用對角線計算矩形面積的公式
以下是根據對角線計算矩形面積的公式:
Area = Width(√ (Diagonal)2 - (Width)2)
示例
以下程式展示瞭如何使用對角線計算矩形的面積。
import Foundation import Glibc var RectDiagonal = 30.0 var RectWidth = 10.0 // Finding the area of the rectangle in terms of diagonals var RectArea = RectWidth * (sqrt(pow(RectDiagonal, 2) - pow(RectWidth, 2))) print("Diagonal - ", RectDiagonal) print("Width - ", RectWidth) print("So, Area of the rectangle- ", RectArea)
輸出
Diagonal - 30.0 Width - 10.0 So, Area of the rectangle- 282.842712474619
在上面的程式碼中,我們使用公式藉助對角線和寬來計算矩形的面積:
var RectArea = RectWidth * (sqrt(pow(RectDiagonal, 2) - pow(RectWidth, 2)))
這裡我們使用 sqrt() 函式計算平方根,並使用 pow() 函式計算冪。因此,上面程式碼的工作原理是
ReactArea = 10.0 * (sqrt(pow(30.0, 2) - pow(10.0, 2))) = 10.0 * (sqrt(900 - 100)) = 10.0 * (sqrt(800)) = 10.0 * (28.2842712474619) = 282.842712474619
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP