Haskell程序:计算平行四边形的面积


本教程讨论了如何编写一个使用Haskell编程语言打印平行四边形面积的程序。

平行四边形是一种四边形,其对边大小相等且平行。

在本教程中,我们将看到三种实现方法:

  • 使用高和底计算平行四边形面积的程序。
  • 使用边长计算平行四边形面积的程序。
  • 使用对角线计算平行四边形面积的程序。

算法步骤

  • 输入或初始化平行四边形尺寸的变量。
  • 实现计算平行四边形面积的程序逻辑。
  • 打印或显示面积。

示例1

使用高和底计算平行四边形面积的程序。

main :: IO()
main = do
-- declaring and initializing the variable for base and height
   let base = 5
   let height = 6
-- computing area
   let area = base * height
-- printing the area
   print ("Area of the parallelogram with base "++ show base ++ " and height " ++ show height ++ " is:")
   print (area)

输出

"Area of the parallelogram with base 5 and height 6 is:"
30

注意 − `show` 函数将数字解析为字符串。它以数字为参数,并返回解析后的字符串。“++”是连接字符串的操作符。

在上面的程序中,我们声明并初始化了底和高的变量。底和高已知的平行四边形的面积可以通过底*高计算。我们通过将底乘以高并将结果加载到变量 `area` 中来计算面积。最后,我们打印了平行四边形的面积。

示例2

使用边长计算平行四边形面积的程序。

main :: IO()
main = do
-- declaring and initializing the variable for sides and angle
   let a = 5
   let b = 6
   let angle = pi/4
-- computing area
   let area = a*b*(sin angle)
-- printing the area
   print ("Area of the parallelogram with sides "++ show a ++ " " ++ show b ++ " and angle between them " ++ show angle)
   print (area)

输出

"Area of the parallelogram with sides 5.0 6.0 and angle between them 0.7853"
21.213203435596423

在上面的程序中,我们声明并初始化了边长和它们之间角度的变量。如果平行四边形的边长分别为a和b,它们之间的角度为k,则面积为a*b*sin(k)。我们计算了面积并将其加载到变量 `area` 中。最后,我们打印了平行四边形的面积。

示例3

使用对角线计算平行四边形面积的程序。

main :: IO()
main = do
-- declaring and initializing the variable for base and height
   let d1 = 6
   let d2 = 8
   let angle = pi/3
-- computing area
   let area = (0.5)*d1*d2*(sin angle)
-- printing the area
   print ("Area of the parallelogram with diagonals "++ show d1 ++ " " ++ show d2 ++ " and angle between them " ++ show angle)
   print (area)

输出

"Area of the parallelogram with diagonals 6.0 8.0 and angle between them 1.047197"
20.784609690826528

在上面的程序中,我们声明并初始化了对角线和它们之间角度的变量。如果平行四边形的对角线为d1、d2,它们之间的角度为k,则面积为½*d1*d2*sin(k)。我们计算了面积并将其加载到变量 `area` 中。最后,我们打印了面积。

结论

在本教程中,我们讨论了三种使用Haskell编程语言实现计算平行四边形面积程序的方法。

更新于:2022年12月14日

浏览量:193

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.