Golang 程序使用库函数获取浮点数的余数
在本文中,我们将讨论如何使用 Go 语言中的库函数获取浮点数的余数。
在编程中,浮点数是一个带有小数点的数字。例如:0.2、5.89、20.79 等。
余数:除法中的余数定义为除法过程结束后剩下的结果。例如,如果被除数为 4,除数为 2,则用 2 除 4 后余数为 0。同样,用 3 除 4 后余数为 1。
要获取浮点值的余数,我们可以使用 math.Mod() 库函数。 mod() 函数的语法定义如下:-
func mod(x, y float64) float64.
此函数接受两个浮点数据类型的参数。这里它们由 x 和 y 表示,其中 x 是被除数,y 是除数。此函数将余数作为浮点数返回。
使用库函数获取浮点数余数的源代码编译并执行如下。
算法
步骤 1 - 导入包 fmt 和 math。
步骤 2 - 启动 main() 函数。
步骤 3 - 初始化浮点数据类型的变量并为其赋值。
步骤 4 - 实现逻辑。
步骤 5 - 在屏幕上打印结果。
示例
package main import ( "fmt" "math" ) // fmt 包允许我们在屏幕上打印任何内容。 // math 包允许我们使用预定义的数学方法,如 mod()。 // 调用 main() 函数 func main() { // initializing the variables to store the dividend, divisor and result respectively. var dividend, divisor, result float64 // assigning values of the dividend and the divisor dividend = 36.5 divisor = 3 // performing the division and storing the results result = math.Mod(dividend, divisor) // printing the results on the screen fmt.Println("The remainder of ", dividend, "/", divisor, "is: ") // limiting the result upto two decimal points fmt.Printf("%.2f", result) }
输出
The remainder of 36.5 / 3 is: 0.50
代码说明
首先,我们分别导入 fmt 包和 math 包,它们允许我们在屏幕上打印任何内容并使用数学方法。
然后我们调用 main() 函数。
之后,我们必须初始化浮点数据类型的 64 位变量,以分配被除数、除数的值并存储结果。
请注意,我们已经初始化了 64 位变量,因为 mod() 函数接受 64 位数字作为参数。
调用 math 包中定义的 Mod() 方法,并将被除数和除数的值作为参数传递给它。
将函数返回的值存储在上面创建的单独变量中作为结果。
使用 fmt.Println() 在屏幕上打印最终结果函数。
算法
步骤 1 - 导入包 fmt 和 math。
步骤 2 - 初始化并定义 getRemainder() 函数。
步骤 3 - 启动 main() 函数。
步骤 4 - 初始化数据类型为 float 的变量,并在其中分配被除数和除数的值。
步骤 5 - 调用 getRemainder() 函数。
步骤 6 - 将其结果存储在变量中。
步骤 7 - 在屏幕。
示例
使用此方法获取浮点数余数的源代码已编译并执行如下。
package main import ( "fmt" "math" ) // fmt 包允许我们在屏幕上打印任何内容。 // math 包允许我们使用其他预定义的数学方法,如 mod()。 // 创建和定义 getRemainder() 函数。 func getRemainder(dividend, divisor float64) float64 { // initializing a 64 bit value variable to store the result of division process var value float64 // performing the division and storing the results value = math.Mod(dividend, divisor) // returning the value of result return value } // 调用 main() 函数 func main() { // initializing the variables to store the dividend, divisor and result respectively. var dividend, divisor, result float64 // storing the values of dividend and divisor in the variables dividend = 20.5 divisor = 5 // storing the result result = getRemainder(dividend, divisor) // printing the results on the screen fmt.Println("The remainder of ", dividend, "/", divisor, "is: ") // limiting the result upto two decimal points fmt.Printf("%.2f", result) }
输出
The remainder of 20.5 / 5 is: 0.50
代码说明
首先,我们必须分别导入 fmt 包和 math 包,它们允许我们在屏幕上打印任何内容并使用数学方法。
然后,我们创建并定义了 getRemainder() 函数,该函数将处理逻辑并在完成所有操作后返回最终值。
之后,我们必须初始化并分配被除数和除数的值。
请注意,我们已经初始化了 64 位变量,因为 mod() 函数接受 64 位数字作为参数。
然后,我们必须调用 getRemainder() 函数并将被除数和除数的值作为参数传递。
在 getRemainder() 函数中,我们使用 math.Mod() 方法来实现逻辑。
返回除法结果的值,在本例中为余数。
将函数返回的值存储在单独的变量中。我们将其命名为result。
使用fmt.Println()函数将结果打印在屏幕上。
结论
我们已经成功编译并执行了Go语言程序,使用库函数和示例获取浮点数的余数。