Golang 如何找到给定弧度值的正切
弧度的相邻边和对边的比值被称为给定弧度的正切。Golang语言有许多预定义函数的包,开发者可以直接使用,无需编写完整的逻辑。我们将使用Golang中的 math 包来执行数学运算和逻辑。通过写一个Golang代码,我们将使用该包来找到给定弧度值的正切,并展示如何导入包以及调用该包中的函数。
正切
定义
正切是三角函数的一部分。要理解正切,观察下面的图示。
如果我们利用上面的图示来定义正切。角度 \theta 的正切函数等于对边和相邻边的比值。
tan \theta = 对边 / 相邻边
不同角度下正切的值
- tan(0) = 0
-
tan(30) = 1 / √3
-
tan(45) = 1
-
tan(60) = √3
-
tan(90) = 未定义
-
tan(120) = − √3
-
tan(135) = − 1
-
tan(150) = −1 / √3
-
tan(180) = 0
图
现在我们来看一下正切函数的图形,并在图形上观察上述值。对于零度角,值为零,然后直到角度成为90度,值为未定义。然后再直到180度,我们将在第四象限中得到一个镜像。
步骤
步骤1 − 声明一个用于保存正切变量的值和浮点数答案的变量。
步骤2 − 初始化一个弧度变量。
步骤3 − 调用正切函数并传递弧度值。
步骤4 − 打印结果。
示例1
在这个示例中,我们将编写一个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 Tangent of a given radian value in the Golang programming language using a math package.")
// initializing the value of the radian value
radianValue = 4.5
// finding tangent for the given radian value
answer = math.Tan(radianValue)
// printing the result
fmt.Println("The Tangent value with the value of radian", radianValue, "is", answer)
}
输出
Program to find the Tangent of a given radian value in the Golang programming language using a math package.
The Tangent value with the value of radian 4.5 is 4.637332054551185
示例2
在这个示例中,我们将编写一个Golang程序,其中我们将导入一个 math 包,并在一个单独的函数中调用正切函数,并调用该函数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 Tangent(angle float64) float64 {
// returning the Tangent of the angle
return math.Tan(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 Tangent 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 factorial of n
answer = Tangent(radianValue)
// finding tangent for the given radian value in the separate function
fmt.Println("The Tangent value with the value of radian", radianValue, "is", answer)
}
输出
Program to find the Tangent of a given radian value in the Golang programming language using a separate function in the same program.
The Tangent value with the value of radian 4.5 is 4.637332054551185
结论
这是通过使用math包中的函数并将弧度值作为参数传递来查找正切的两种方法。如果我们比较这两种方法,那么创建一个单独的函数的第二种方法将通过创建一个独立的函数在程序中提供抽象,并且可以在不同的地方重复使用。要了解更多关于Golang的信息,您可以探索这些tutorials。