Swift程式設計:計算等邊三角形的面積和周長
本教程將討論如何編寫Swift程式來計算等邊三角形的面積和周長。
等邊三角形是指所有邊和角都相等的一個三角形。等邊三角形的每個角都是60度。它也被稱為三邊多邊形。
等邊三角形的面積
三角形三條線之間所佔的空間量稱為等邊三角形的面積。
公式
以下是公式:
Area = √3x2/ 4
這裡x是等邊三角形的邊長。
以下是演示:
輸入
假設我們的給定輸入是:
Side = 4
輸出
期望輸出為:
Area of the equilateral triangle: 6.928203230275509
演算法
以下是演算法:
步驟1 - 建立一個具有返回值的函式。
步驟2 - 使用以下公式計算等邊三角形的面積:
let result = (sqrt(3) * side * side)/4
步驟3 - 呼叫函式並將邊長作為引數傳遞給函式。
步驟4 - 列印輸出。
示例
下面的程式演示瞭如何計算等邊三角形的面積。
import Foundation import Glibc // Creating a function to calculate area of the equilateral triangle func equiTriangle(side: Double){ let result = (sqrt(3) * side * side)/4 print("Area of the equilateral triangle: \(result)") } // Side of the equilateral triangle var x = 10.0 print("Side: \(x)") // Calling function equiTriangle(side:x)
輸出
Side: 10.0 Area of the equilateral triangle: 43.301270189221924
在上面的程式中,我們建立了一個函式,使用以下公式返回等邊三角形的面積:
let result = (sqrt(3) * side * side)/4
這裡我們輸入邊長side = 10,因此面積為43.301270189221924。
等邊三角形的周長
等邊三角形邊緣的距離稱為等邊三角形的周長。
公式
以下是公式:
Perimeter = 3x
這裡x是等邊三角形的邊長。
以下是演示:
輸入
假設我們的給定輸入是:
Side = 7
輸出
期望輸出為:
Perimeter of the equilateral triangle: 21
演算法
以下是演算法:
步驟1 - 建立一個具有返回值的函式。
步驟2 - 使用以下公式計算等邊三角形的周長:
let result = 3 * side
步驟3 - 呼叫函式並將邊長作為引數傳遞給函式。
步驟4 - 列印輸出。
示例
下面的程式演示瞭如何計算等邊三角形的周長。
import Foundation import Glibc // Creating a function to calculate the perimeter // of the equilateral triangle. func periTriangle(side: Int){ let result = 3 * side print("Perimeter of the equilateral triangle: \(result)") } // Side of the equilateral triangle var x = 4 print("Side: \(x)") // Calling function periTriangle(side:x)
輸出
Side: 4 Perimeter of the equilateral triangle: 12
在上面的程式中,我們建立了一個函式,使用以下公式返回等邊三角形的周長:
let result = 3 * side
這裡我們輸入邊長side = 4,因此中點是12。
廣告