To find the square root of a number in Golang:
- Import the package math in the golang program
- Use the Sqrt() function, it takes a number as an input parameter.
- It returns the square root of a number.
Syntax
func Sqrt(x float64) float64
Where,
Parameter: x as input number of type float64
Return: It returns the square root of x of type float64
Special Cases for Square Root are:
Sqrt(+Inf) = +Inf
Sqrt(±0) = ±0
Sqrt(x < 0) = NaN
Sqrt(NaN) = NaN
In this article, we will discuss how to calculate the square root of a number in golang.
How to Calculate the Square Root of a Number in Golang
To calculate the square root of a number in golang, you can use the Sqrt() method of the math package.
package main import ( "fmt" "math" ) // Main function func main() { // Finding square root of the given number // Using Sqrt() function ans1 := math.Sqrt(0) fmt.Printf("Square Root of 0: %.1f", ans1) ans2 := math.Sqrt(4) fmt.Printf("\nSquare Root of 4: %.1f", ans2) ans3 := math.Sqrt(math.NaN()) fmt.Printf("\nSquare Root of NAN: %.1f", ans3) ans4 := math.Sqrt(-64) fmt.Printf("\nSquare Root of Negative Number: %.1f", ans4) ans5 := math.Sqrt(math.Inf(1)) fmt.Printf("\nSquare Root of Infinity: %.1f", ans5) }
Output
Square Root of 0: 0.0
Square Root of 4: 2.0
Square Root of NAN: NaN
Square Root of Negative Number: NaN
Square Root of Infinity: +Inf
In the above golang program, we import the math package and use the Sqrt function to get the square root for a given number.
Conclusion
I hope the above article helped you to find the square root of a given number in golang.
You can find more topics about the Golang tutorials on the GolangSpot Home page.