Haskell程式計算菱形面積
在Haskell中,有多種計算菱形面積的方法。我們可以使用邊長、對角線和高,根據這些,可以透過不同的方法計算出它的面積。
演算法
步驟1 - 匯入Text.Printf模組。
步驟2 - 定義Rhombus函式。
步驟3 - 程式執行將從main函式開始。main()函式控制整個程式。它被寫成main = do。它接收兩個整數作為對角線,並使用rhombusArea函式列印面積。
步驟4 - 初始化名為“d1”和“d2”的變數。它們將儲存菱形的兩個整數對角線。
步驟5 - 使用'printf'函式將菱形的面積結果列印到控制檯。printf函式用於將輸出格式化為兩位小數。
示例1
在這個例子中,定義了一個函式rhombusArea,它接收菱形的兩個對角線作為引數,並使用公式(d1 * d2) / 2返回面積。
import Text.Printf rhombusArea :: Double -> Double -> Double rhombusArea d1 d2 = (d1 * d2) / 2 main :: IO () main = do let d1 = 4 let d2 = 5 let area = rhombusArea d1 d2 printf "Area of the rhombus: %.2f" area
輸出
Area of the rhombus: 10.00
示例2
在這個例子中,菱形的邊長作為輸入,並使用公式(s1*s2)/2計算面積。
import Text.Printf rhombusArea :: Double -> Double -> Double rhombusArea s1 s2 = (s1 * s2) / 2 main :: IO () main = do let s1 = 4 let s2 = 5 let area = rhombusArea s1 s2 printf "Area of the rhombus: %.2f" area
輸出
Area of the rhombus: 10.00
示例3
在這個例子中,菱形的一條邊長和高作為輸入,然後使用公式s*h計算面積。
import Text.Printf rhombusArea :: Double -> Double -> Double rhombusArea s h = s * h main :: IO () main = do let s = 4 let h = 5 let area = rhombusArea s h printf "Area of the rhombus: %.2f" area
輸出
Area of the rhombus: 20.00
結論
Haskell中可以透過使用對角線、邊長或使用一邊長和高來計算菱形的面積。在呼叫定義的函式時,面積使用'printf'函式列印到控制檯。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP