如何在 Golang 中乘以两个浮点数?


本教程将演示如何在函数内或通过创建单独的函数并在当前函数中调用它来乘以两个浮点数。

在函数内乘以两个浮点数

算法

  • 步骤 1 - 定义我们要乘以的浮点变量以及我们将存储结果的浮点变量。

  • 步骤 2 - 使用要乘以的相应值初始化变量。

  • 步骤 3 - 将两个数字相乘并将结果存储在第三个变量中。

  • 步骤 4 - 打印两个数字相乘后的结果。

示例

Open Compiler
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 - 打印两个数字相乘后的结果。

示例

Open Compiler
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 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告