Go语言程序:计算长方体的体积、对角线和表面积?


在本教程中,我们将讨论如何使用长方体的长、宽和高来计算长方体的体积、对角线和表面积。

但在编写 Go 语言代码之前,让我们简要讨论一下长方体及其体积、对角线和表面积。

长方体

长方体是一个三维图形,具有六个面和十二条边。与所有边都相等的长方体不同,长方体的长、宽和高是不同的。一个矩形盒子就是一个长方体的很好的例子。

长方体的体积

长方体占据的空间量称为其体积。在我们需要知道房间内可以容纳多少空气的情况下,计算长方体的体积可能会有益。

Volume = l * b * h

长方体的对角线

长方体的对角线可以定义为连接长方体两个相对顶点的线段。

$$\mathrm{对角线\: = \:\sqrt({l^2 + b^2 +h^2})}$$

长方体的表面积

长方体占据的总面积称为长方体的表面积。

Area = 2 * (l * h + l * b + h * b)

示例

  • 长 = 10,宽 = 3,高 = 5

    长方体的体积 = 150

    长方体的对角线 = 11.575836902790225

    长方体的表面积 = 190

解释

$\mathrm{长方体的体积\: = \:l * b * h}$

$\mathrm{= \:10 * 3 * 5}$

$\mathrm{=\: 150}$

$\mathrm{长方体的对角线\: = \:\sqrt({l^2 + b^2 +h^2})}$

$\mathrm{\:\sqrt({l0^2 +3^2 +5^2})}$

$\mathrm{= 11.575836902790225}$

$\mathrm{长方体的表面积\: = \:2 * (l * h + l * b + h * b)}$

$\mathrm{= \:2 * (10 * 5 + 10 * 3 + 5 * 3)}$

$\mathrm{= \:190}$

计算长方体的体积、对角线和表面积

  • 步骤 1 - 声明三个变量来存储长方体的长 'l'、宽 'b' 和高 'h'。

  • 步骤 2 - 声明三个变量来存储长方体的体积 'volume'、对角线 'diag' 和表面积 'area',并将所有三个变量初始化为 0。

  • 步骤 3 - 使用公式计算体积 - 体积 = l * b * h,并将其存储在函数 calculateVolumeOfCuboid() 中的 'volume' 变量中。

  • 步骤 4 - 使用公式计算对角线 - 对角线 = √(l2 + b2 +h2),并将其存储在函数 calculateDiagonalOfCuboid() 中的 'diag' 变量中。

  • 步骤 5 - 使用公式计算表面积 - 表面积 = 2 * (l * h + l * b + h * b),并将其存储在函数 calculateAreaOfCuboid() 中的 'area' 变量中。

  • 步骤 6 - 打印计算出的长方体的体积、对角线和表面积,即存储在 'volume'、'diag' 和 'area' 变量中的值。

示例

package main
import (
	"fmt"
	"math"
)
func calculateVolumeOfCuboid(l, b, h float64) float64 {
	var volume float64 = 0
	volume = l * b * h
	return volume
}
func calculateDiagonalOfCuboid(l, b, h float64) float64 {
	var diag float64 = 0
	diag = math.Sqrt((l * l) + (b * b) + (h * h))
	return diag
}
func calculateAreaOfCuboid(l, b, h float64) float64 {
	var area float64 = 0
	area = 2 * ((l * h) + (l * b) + (h * b))
	return area
}
func main() {
   var l, b, h float64 = 10, 3, 5
	var volume, diag, area float64
	fmt.Println("Program to calculate the volume, diagonal and area of the Cuboid \n")
	volume = calculateVolumeOfCuboid(l, b, h)
	diag = calculateDiagonalOfCuboid(l, b, h)
	area = calculateAreaOfCuboid(l, b, h)

	fmt.Println("Length of the cuboid: ", l)
	fmt.Println("Breadth of the cuboid: ", b)
	fmt.Println("Height of the cuboid: ", h)
	fmt.Println("Therefore, Volume of cuboid: ", volume)
	fmt.Println("Diagonal of cuboid: ", diag)
	fmt.Println("Area of cuboid: ", area)
}

输出

Program to calculate the volume, diagonal and area of the Cuboid 

Length of the cuboid:  10
Breadth of the cuboid:  3
Height of the cuboid:  5
Therefore, Volume of cuboid:  150
Diagonal of cuboid:  11.575836902790225
Area of cuboid:  190

代码描述

  • calculateVolumeOfCuboid(l, b, h float64) float64 - 此函数将计算长方体的体积。它具有 float64 的返回类型。

  • diag = math.Sqrt((l * l) + (b * b) + (h * h)) - 使用此公式,我们正在计算对角线。我们使用 math 包中的 Sqrt 函数来进行平方根运算。

结论

这就是使用 Go 编程语言计算长方体的体积、对角线和表面积的全部内容。我们还通过使用单独的函数来计算面积、对角线和体积来保持代码模块化,这也提高了代码的可重用性。您可以使用这些教程探索更多关于 Go 语言编程的信息。

更新于: 2022-12-28

230 次查看

开启您的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.