Golang 如何找到给定弧度值的余弦值
在本教程中,我们将学习如何在Golang编程语言中找到给定弧度值的余弦值。Golang语言具有许多预定义函数的包,开发人员可以在不编写完整逻辑的情况下使用。
要执行数学运算和逻辑操作,我们在Golang中使用 math 包。我们只需使用这个包来找到给定弧度值的余弦值。我们还将看到如何导入该包以及如何通过编写Golang代码来调用该包中的函数。
余弦函数
定义
余弦是三角学中的一个函数。要理解余弦,请观察下面的图表。
如果我们利用上面的图表定义余弦函数。角度Ө的余弦函数等于相邻边与斜边的比值。
cosӨ = 相邻边 / 斜边
不同角度下的余弦值
- cos(0) = 1
-
cos(30) = √3 / 2
-
cos(45) = 1 / √2
-
cos(60) = 1 / 2
-
cos(90) = 0
-
cos(120) = -1 / 2
-
cos(135) = – 1 / √2
-
cos(150) = -√3 / 2
-
cos(180) = – 1
图像
现在我们将看到余弦函数的图像,并观察上述值在图上的位置。对于零度角,值为1,随着角度达到90度,值变为零。然后再从180度开始,我们将在第四象限得到镜像。
步骤
步骤1 - 声明一个变量来存储弧度值和float32类型的答案。
步骤2 - 初始化弧度的变量。
步骤3 - 调用余弦函数并传入弧度值。
步骤4 - 打印结果。
示例
在这个示例中,我们将编写一个Golang程序,导入 math 包并调用余弦函数。
package main
import (
// fmt package provides the function to print anything
"fmt"
// math package provides multiple functions for different
// mathematical operations
"math"
)
func main() {
// declaring the variables to store the value of radian value and answer
var radianValue, answer float64
fmt.Println("Program to find the cosine of a given radian value in the Golang programming language using a math package.")
// initializing the value of radian value
radianValue = 4.5
// finding cosine for the given radian value
answer = math.Cos(radianValue)
// printing the result
fmt.Println("The cosine value with the value of radian", radianValue, "is", answer)
}
输出
Program to find the cosine of a given radian value in the Golang programming language using a math package.
The cosine value with the value of radian 4.5 is -0.21079579943077972
步骤
步骤1 - 声明一个变量,用于存储守护者的值和浮点值的答案。
步骤2 - 初始化弧度变量。
步骤3 - 调用我们定义的余弦函数,并将弧度值作为参数传递。
步骤4 - 打印结果。
示例
在这个示例中,我们将编写一个Golang程序,导入一个 math 包,并在一个单独的函数中调用cosine函数,然后调用该函数main。
package main
import (
// fmt package provides the function to print anything
"fmt"
// math package provides multiple functions for different
// mathematical operations
"math"
)
// this is a function with a parameter of float64 type and a return type of float64
func Cosine(angle float64) float64 {
// returning the cosine of the angle
return math.Cos(angle)
}
func main() {
// declaring the variables to store the value of radian value and answer
var radianValue, answer float64
fmt.Println("Program to find the cosine of a given radian value in the Golang programming language using a separate function in the same program.")
// initializing the value of the radian value
radianValue = 4.5
// finding cosine for the given radian value in separate function
answer = Cosine(radianValue)
// printing the result
fmt.Println("The cosine value with the value of radian", radianValue, "is", answer)
}
输出
Program to find the cosine of a given radian value in the Golang programming language using a separate function in the same program.
The cosine value with the value of radian 4.5 is -0.21079579943077972
结论
这是两种通过使用 math 包中的函数并将弧度值作为参数来找到余弦的方法。第二种方法可以在程序中提供抽象化。想要了解更多关于Golang的知识,可以参考这些教程。