如何在 Golang 中乘以兩個浮點數?


本教程將演示如何在函式內或透過建立單獨的函式並在當前函式中呼叫它來乘以兩個浮點數。

在函式內乘以兩個浮點數

演算法

  • 步驟 1 - 定義我們要乘以的浮點變數以及我們將儲存結果的浮點變數。

  • 步驟 2 - 使用要乘以的相應值初始化變數。

  • 步驟 3 - 將兩個數字相乘並將結果儲存在第三個變數中。

  • 步驟 4 - 列印兩個數字相乘後的結果。

示例

package main // fmt package provides the function to print anything import "fmt" func main() { // declaring the variables of type float var num1, num2, num3 float32 // initializing the variables which we have to multiply num1 = 25.5 num2 = 23.333 // multiplying the float variables and storing them into a third variable num3 = num1 * num2 // printing the multiplication of two numbers fmt.Println("Multiplication of", num1, "and", num2, "=\n", num3,"\n(multiplying within the function)") }

在上述函式中,我們首先宣告三個浮點型變數。然後,我們用要乘以的浮點數初始化其中的兩個。在此步驟中,我們正在將數字相乘並將它們儲存在第三個數字中。最後,我們列印結果。

輸出

Multiplication of 25.5 and 23.333 =
594.9915
(multiplying within the function)

在函式外部乘以兩個浮點數

演算法

  • 步驟 1 - 定義我們要乘以的浮點變數以及我們將儲存結果的浮點變數。

  • 步驟 2 - 使用要乘以的相應值初始化變數。

  • 步驟 3 - 透過呼叫multiplyFloatNumber()函式將兩個數字相乘並將結果儲存在第三個變數中。

  • 步驟 4 - 列印兩個數字相乘後的結果。

示例

package main // fmt package provides the function to print anything import "fmt" func multiplyFloatNumber(num1, num2 float32) float32 { return num1 * num2 } func main() { // declaring the variables of type float var num1, num2, num3 float32 // initializing the variables which we have to multiply num1 = 25.5 num2 = 23.333 // multiplying the float variables and storing them into a third variable num3 = multiplyFloatNumber(num1, num2) // printing the result fmt.Println("Multiplication of", num1, "and", num2, "=\n", num3, "\n(multiplying outside the function)") }

在上述函式中,我們首先宣告三個浮點型變數。然後,我們用要乘以的浮點數初始化其中的兩個。在此步驟中,我們透過呼叫multiplyFloatNumber()函式將數字相乘並將結果儲存在第三個數字中。最後,我們列印結果。

multiplyFloatNumber(num1, num2 float32) float32 的描述。

  • (num1, num2 float32) - 這是 Golang 中建立函式作為引數的方式。在此函式中,我們有兩個 float32 型別的引數。

  • func multiplyFloatNumber(num1, num2 float32) float32 - 函式定義末尾的 float32 表示函式的返回型別,對於此函式,返回型別為 float32。

輸出

Multiplication of 25.5 and 23.333 =
594.9915
(multiplying outside the function)

透過這些方式,我們可以將兩個浮點數相乘。為了使程式碼更具可讀性和模組化,我們可以採用第二種方法。因為,透過為函式指定適當的名稱,即使不瞭解相應程式語言的人也可以理解程式碼。本文就是關於這個的,要了解更多關於 Golang 的資訊,您可以參考這些教程。

更新於: 2022-08-26

914 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.