Golang 如何相乘两个浮点数
本教程将展示如何在函数内部相乘两个浮点数,或者通过创建一个独立的函数并在当前函数中调用它来实现。
在函数内部相乘两个浮点数
步骤
- 第一步 - 定义我们要相乘的浮点变量,以及我们将把结果添加到的浮点变量。
-
第二步 - 使用您要相乘的相应值初始化变量。
-
第三步 - 相乘两个数并将结果存储在第三个变量中。
-
第四步 - 在乘以两个数后打印结果。
示例
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)")
}
在上述函数中,首先我们声明了三个float类型的变量。然后,我们用我们想要相乘的浮点数对其中两个进行初始化。在这一步中,我们通过调用 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的内容,想要了解更多可以参考这些教程。