Haskell程式:計算矩形面積


本教程討論如何使用Haskell程式語言編寫一個程式來列印矩形的面積。

矩形是一種四邊形,其對邊長度相等,相鄰邊成直角。矩形的面積等於其長和寬的乘積。如果矩形的長和寬分別為5和6,則面積為30個單位(5*6)。

在本教程中,我們將看到四種實現方法:

  • 使用中綴運算子“*”計算矩形面積的程式。

  • 使用運算子函式“(*)”計算矩形面積的程式。

  • 使用對角線(已知長或寬之一)計算矩形面積的程式。

  • 使用周長(已知長或寬之一)計算矩形面積的程式。

演算法步驟

  • 輸入或初始化矩形尺寸的變數。
  • 實現計算矩形面積的程式邏輯。
  • 列印或顯示面積。

示例1

使用中綴運算子“*”計算矩形面積的程式

main ::IO()
main = do
-- initializing and declaring a variable for the length and breadth of the rectangle
 let len = 5
 let bred = 6
-- computing the area
 let area = len*bred
-- printing the computed area
 print ("Area of the rectangle with length "++ show len ++ "and breadth " ++ show bred ++" units is:")
 print (area)

輸出

"Area of the rectangle with length 5 and breadth 6 units is:"
30

注意 − show函式將數字解析為字串。它以數字為引數,返回解析後的字串。“++”是連線字串的運算子。

在上面的程式中,我們宣告並初始化變數來儲存矩形的長和寬。我們使用乘法的中綴運算子(“*”)將長乘以寬來計算矩形的面積,並將計算出的值載入到變數area中。最後,我們使用print函式列印面積。

示例2

使用運算子函式(“(*)”)計算矩形面積的程式

main ::IO()
main = do
-- initializing and declaring a variable for the length and breadth of the rectangle
   let len = 5
   let bred = 6
-- computing the area
   let area =(*) len bred
-- printing the computed area
   print ("Area of the rectangle with length "++ show len ++ " and breadth " ++ show bred ++" units is:")
   print (area)

輸出

"Area of the rectangle with length 5 and breadth 6 units is:"
30

在上面的程式中,我們宣告並初始化變數來儲存矩形的長和寬。我們使用乘法的函式運算子(“(*)”)透過傳遞長和寬作為引數並將其計算出的返回值載入到變數area中來計算矩形的面積。最後,我們使用print函式列印面積。

注意 − 中綴運算子可以透過用圓括號括起來轉換為運算子函式。然後可以將它們用作普通函式。

示例3

使用對角線(已知長或寬之一)計算矩形面積的程式

main ::IO()
main = do
-- initializing and declaring a variable for the length and breadth of the rectangle
   let len = 5
   let diagonal = 13
-- computing the breadth
   let breadth = sqrt (diagonal^2 - len^2)
-- computing the area
   let area = len*breadth
-- printing the computed area
   print ("Area of the rectangle with length "++ show len ++ " and diagonal " ++ show diagonal ++" units is:")
   print (area)

輸出

"Area of the rectangle with length 5.0 and diagonal 13.0 units is:"
60.0

在上面,我們宣告並初始化了矩形長和對角線的變數。我們使用勾股定理從長和對角線計算矩形的寬。透過將長和寬相乘計算面積。將計算出的面積載入到變數area中。最後,列印矩形的面積。

示例4

使用周長(已知長或寬之一)計算矩形面積的程式。

main ::IO()
main = do
-- initializing and declaring a variable for the length and breadth of the rectangle
   let len = 5
   let perimeter = 22
-- computing the breadth
   let breadth = (perimeter - len*2)/2
-- computing the area
   let area = len*breadth
-- printing the computed area
   print ("Area of the rectangle with length "++ show len ++ " and perimeter " ++ show perimeter ++" units is:")
   print (area)

輸出

"Area of the rectangle with length 5.0 and perimeter 22.0 units is:"
30.0

注意 − 在矩形中,對邊長度相同,即2*長和2*寬等於矩形的周長。如果我們知道周長和長或寬之一,我們可以計算長或寬。

在上面的程式中。我們宣告並初始化了矩形長和周長的變數。我們從周長和長計算矩形的寬。透過將長和寬相乘計算面積。將計算出的面積載入到變數area中。最後,列印矩形的面積。

結論

在本教程中,我們討論了四種使用Haskell程式語言實現計算矩形面積程式的方法。

更新於:2022年12月14日

瀏覽量:358

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.