为了更好地理解这个示例,我们始终建议您学习下面列出的 Golang 编程 的基础主题
长方体的表面积是所有 6 个面的面积之和。
如果我们用长度 (l)、宽度 (w) 和高度 (h) 表示,那么
长方体的表面积 = 2lw + 2lh + 2wh
长方体的体积是长度、宽度和高度的乘积
长方体的体积 = lbh
长方体的侧面积是长方体表面积中不包括顶部和底部的面积。侧面积的公式是
长方体的侧面积 = 2h (l + w)
其中 l = 长度,w = 宽度,h = 高度
这里我们展示如何在 Go 语言中求长方体的体积和表面积。这里变量 len, Wid, Hght 存储长方体的长度、宽度、高度。其他变量 SA, Vol, LA 用作表面积、体积、侧面积的结果变量。使用数学函数进行计算。体积通过 lbh 求得,表面积通过 2lw + 2lh + 2wh 求得。最后打印结果。下面是在 Go 程序中使用的步骤。
第一步:导入 fmt 包
第二步:启动 main() 函数
第 3 步:声明变量 len, Wid, Hght, SA, Vol, LA
第 4 步:读取长方体的长度、宽度、高度 len, Wid, Hght
第 5 步:使用 2lw + 2lh + 2wh 计算表面积
第 6 步: 使用 lbh 计算体积
第 7 步:使用 2h (l + w) 计算侧面积
第 8 步: 使用 fmt.Println() 打印 SA, Vol, LA
package main
import "fmt"
func main() {
var len, Wid, Hght, SA, Volu, LA float32
fmt.Print("Enter the length of a cuboid = ")
fmt.Scanln(&len;)
fmt.Print("Enter the width of a cuboid = ")
fmt.Scanln(&Wid;)
fmt.Print("Enter the height of a cuboid = ")
fmt.Scanln(&Hght;)
SA = 2 * (len*Wid + len*Hght + Wid*Hght)
Vol = len * Wid * Hght
LA = 2 * Hght * (len + Wid)
fmt.Println("\nThe volume of a cuboid = ", Vol)
fmt.Println("The surface area of a cuboid = ", SA)
fmt.Println("Lateral surface area of a cuboid = ", LA)
}
Enter the length of a cuboid = 8 Enter the width of a cuboid = 5 Enter the height of a cuboid = 6 The volume of a cuboid = 240 The surface area of a cuboid = 236 Lateral surface area of a cuboid = 156