Square root of a negative number

Report a typo

Lena has created a Go program that calculates the square root of any positive (decimal) number using the math.Sqrt function. However, one of her friends tried to calculate the square root of a negative number and got NaN (not-a-number) answer.

To fix this issue, Lena wants to use the errors.New() function and create a custom error message within the negativeNumError function that shows up when users try to calculate the square root of a negative number.

The contents of the error message should be the following string: "math: can't calculate square root of negative number".

Please help Lena create the custom error message; below is the code she has written so far:

Sample Input 1:

-1

Sample Output 1:

math: can't calculate square root of negative number

Sample Input 2:

4

Sample Output 2:

2
Write a program in Go
package main

import (
"errors"
"fmt"
"math"
)

func negativeNumError() error {
// create a custom error message within the 'err' variable here
err := ?

return err
}

// DO NOT delete or modify the code within the main() function!
func main() {
var num float64
fmt.Scanf("%f", &num)

if num < 0 {
err := negativeNumError()
fmt.Println(err)
return
}
fmt.Println(math.Sqrt(num))
}
___

Create a free account to access the full topic