Haskell程式:計算圓柱體的體積和表面積
本教程將幫助我們計算圓柱體的體積和表面積。圓柱體的體積是圓柱體內空間大小的度量。表面積是指圓柱體的表面積。圓柱體體積的公式是圓柱體底面積(πr^2)乘以高h的積。圓柱體表面積的公式是兩個圓形面的面積與矩形側面面積之和。
演算法
步驟 1 − 匯入Text.Printf模組。
步驟 2 − 根據簡單的數學公式定義體積和表面積函式,分別為體積 r h = pi * r * r * h 和表面積 r h = (2 * pi * r * h) + (2 * pi * r * r)。
步驟 3 − 程式執行將從主函式開始。main() 函式控制整個程式。它寫成 main = do。主函式獲取圓柱體的半徑和高度,然後呼叫體積和表面積函式來計算結果。
步驟 4 − 初始化名為“radius”和“height”的變數。它們將分別包含要計算其面積和體積的圓柱體的半徑和高度。
步驟 5 − 呼叫體積和表面積函式後,使用‘printf’語句顯示最終的體積和表面積值。
使用使用者定義的面積和體積函式
在這個例子中,定義了兩個函式,volume 和 area,它們分別以圓柱體的半徑和高度作為引數,並返回其體積和表面積。
示例 1
import Text.Printf volume :: Double -> Double -> Double volume r h = pi * r * r * h area :: Double -> Double -> Double area r h = (2 * pi * r * h) + (2 * pi * r * r) main :: IO () main = do let radius = 5 let height = 10 let vol = volume radius height let ar = area radius height printf "Volume of the cylinder is: %.2f
" vol printf "Surface area of the cylinder is: %.2f
" ar
輸出
Volume of the cylinder is: 785.40 Surface area of the cylinder is: 471.24
使用 $ 運算子和 print 函式
此方法使用 $ 運算子將右側的函式應用於左側的引數,有效地減少了對函式呼叫周圍括號的需求。最後,它使用 print 函式將結果列印到控制檯。
示例 2
import Text.Printf volume :: Double -> Double -> Double volume r h = pi * r * r * h area :: Double -> Double -> Double area r h = (2 * pi * r * h) + (2 * pi * r * r) main :: IO () main = do let radius = 5 let height = 10 print $ "Volume of the cylinder is: " ++ show (volume radius height) print $ "Surface area of the cylinder is: " ++ show (area radius height)
輸出
"Volume of the cylinder is: 785.3981633974483" "Surface area of the cylinder is: 471.23889803846896"
結論
有多種計算圓柱體體積和表面積的示例,但計算圓柱體體積和表面積的數學公式始終保持不變。在 Haskell 中,可以使用使用者定義的函式或使用 $ 運算子和 print 函式來計算圓柱體的體積和表面積。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP