博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
A Tour of Go Exercise: Errors
阅读量:7238 次
发布时间:2019-06-29

本文共 1227 字,大约阅读时间需要 4 分钟。

Copy your Sqrt function from the earlier exercises 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".

Note: a call to fmt.Print(e) inside the Error method will send the program into an infinite loop. You can avoid this by converting e first:fmt.Print(float64(e)). Why?

Change your Sqrt function to return an ErrNegativeSqrt value when given a negative number.

package mainimport (    "fmt"    "strconv")type ErrNegativeSqrt float64func (e ErrNegativeSqrt) Error() string{    if e < 0 {        return "cannot Sqrt negative number:" + strconv.FormatFloat(float64(e),'f',5,64)    }    return ""}func Sqrt(f float64) (float64, error) {    var e error    if f < 0 {        return 0,ErrNegativeSqrt(f)    }    var z float64 = 1    for i := 0; i < 10; i++ {        z = z - (z*z - f) / (2 * z)    }    return z,e}func main() {    fmt.Println(Sqrt(2))    fmt.Println(Sqrt(-2))}

 

转载于:https://www.cnblogs.com/ghgyj/p/4057883.html

你可能感兴趣的文章
Linux 64位操作系统安装配置java
查看>>
SolarCity欲为500万美国家庭搭建太阳能屋顶
查看>>
苹果进军印度市场到底有多难 连财政部长都不帮忙
查看>>
监控摄像机选型攻略之技术类型选用
查看>>
JAVA笔记——序列化
查看>>
《数据科学:R语言实现》——3.1 引言
查看>>
协作软件的前景、进展以及阵痛
查看>>
PyTorch 和 TensorFlow 哪个更好?看一线开发者怎么说
查看>>
怎么善于发现seo网站优化的问题?
查看>>
《Metasploit渗透测试手册》—第8章8.1节介绍
查看>>
《UG NX8.0中文版完全自学手册》一1.4 工具栏的定制
查看>>
合三为一,Linux 基金会欲打造顶级开源峰会
查看>>
《计算机系统:系统架构与操作系统的高度集成》——2.8 编译函数调用
查看>>
Coda 2.5 发布,Mac 编辑器软件
查看>>
Vue.js —— 轻量级 JavaScript 框架(国人开发)
查看>>
《计算机科学导论》一2.1 引言
查看>>
《Linux KVM虚拟化架构实战指南》——2.2 安装配置RHEV虚拟化所需服务器
查看>>
《大型网站服务器容量规划》一3.3 其他容量规划方法
查看>>
《极客与团队》一第一章 天才程序员的传说
查看>>
《Python爬虫开发与项目实战》——3.2 HTTP请求的Python实现
查看>>