Exercise: Errors

題目:

Copy your Sqrt function from the earlier exercise and modify it to return an error value.
Sqrt should return a non-nil error value when given a negative number, as it doesn't support complex numbers.
Create a new type type ErrNegativeSqrt float64
and make it an error by giving it a
func (e ErrNegativeSqrt) Error() string
method such that ErrNegativeSqrt(-2).Error() returns "cannot Sqrt negative number: -2".</br>
Note: a call to fmt.Sprint(e) inside the Error method will send the program into an infinite loop. You can avoid this by converting e first: fmt.Sprint(float64(e)) . Why?</br>
Change your Sqrt function to return an ErrNegativeSqrtvalue when given a negative number.

exercise-errors.go

package main

import (
    "fmt"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot Sqrt negative number: %v", e)
}

func Sqrt(x float64) (float64, error) {
    if (x < 0) {
        return x, ErrNegativeSqrt(x)
    }

    z := 1.0
    for i := 0; i < 10; i++ {
        z = z - (z*z - x)/(2*z);
    }

    return z, nil
}

func main() {
    fmt.Println(Sqrt(2))
    fmt.Println(Sqrt(-2))
}

Note:
上述代碼如果直接運行的話會導致infinite loop,因為 fmt.Sprintf("cannot Sqrt negative number: %v", e)會不斷調用e.Error()轉換成string
所以fmt.Sprintf("cannot Sqrt negative number: %v", e)應改為fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))orfmt.Sprintf("cannot Sqrt negative number: %f", e)。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容