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.