《GO语言圣经》读书笔记 第二章 习题解答

练习 2.1: 向tempconv包添加类型、常量和函数用来处理Kelvin绝对温度的转换,Kelvin 绝对零度是−273.15°C,Kelvin绝对温度1K和摄氏度1°C的单位间隔是一样的


package tempconv

import "fmt"

type Celsius float64
type Fahrenheit float64
type Kelvin float64

const (
    AbsoluteZeroC Celsius = -273.15
    FreezingC Celsius = 0
    BoilingC Celsius = 100
)

func (c Celsius) String() string    { return fmt.Sprintf("%g°C", c) }
func (f Fahrenheit) String() string { return fmt.Sprintf("%g°F", f) }
func (k Kelvin) String() string     { return fmt.Sprintf("%gK", k) }

func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }
func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }

func CToK(c Celsius) Kelvin {return Kelvin(c + AbsoluteZeroC)}
func KToC(k Kelvin) Celsius { return Celsius(k) - AbsoluteZeroC}


package main

import (
    "fmt"
    "./tempconv"
)


func main() {
    fmt.Println("AbsoluteZeroK:",tempconv.CToK(tempconv.AbsoluteZeroC))
    fmt.Println("FreezingK:",tempconv.CToK(tempconv.FreezingC))
    fmt.Println("BoilinigK:",tempconv.CToK(tempconv.BoilingC))
}

练习 2.2: 写一个通用的单位转换程序,用类似cf程序的方式从命令行读取参数,如果缺省的话则是从标准输入读取参数,然后做类似Celsius和Fahrenheit的单位转换,长度单位可以对应英尺和米,重量单位可以对应磅和公斤等

package main

import (
    "fmt"
    "os"
    "bufio"
    "strings"
    "strconv"
    "../ex01/tempconv"
)

type Meter float64
type Feet float64
type Pound float64
type Kilogram float64

func (m Meter) String() string {return fmt.Sprintf("%gm",m)}
func (f Feet) String() string {return fmt.Sprintf("%gft",f)}
func (p Pound) String() string {return fmt.Sprintf("%glb",p)}
func (k Kilogram) String() string {return fmt.Sprintf("%gkg",k)}

func MToF(m Meter) Feet {return Feet(m * 1200 / 3937)}
func FToM(f Feet) Meter {return Meter(f * 3937 / 1200)}
func PToK(p Pound) Kilogram {return Kilogram( p * 0.45359237)}
func KToP(k Kilogram) Pound { return Pound(k / 0.45359237)}


func main() {
    var args []string
    if len(os.Args) > 1 {
        args = os.Args[1:]
    }else{
        r := bufio.NewReader(os.Stdin)
        s, _ := r.ReadString('\n')
        args = []string{strings.TrimSpace(s)}
    }

    for _,arg := range args {
        v, err := strconv.ParseFloat(arg, 64)
        if err != nil {
            fmt.Fprintf(os.Stderr,"unitconv: %v\n",err)
            os.Exit(1)
        }
        {
            f := tempconv.Fahrenheit(v)
            c := tempconv.Celsius(v)
            fmt.Printf("%s = %s,%s = %s\n",f,tempconv.FToC(f),c,tempconv.CToF(c))
        }
        {
            m := Meter(v)
            f := Feet(v)
            fmt.Printf("%s = %s,%s = %s\n",m,MToF(m),f,FToM(f))
        }
        {
            p := Pound(v)
            k := Kilogram(v)
            fmt.Printf("%s = %s, %s = %s\n",p,PToK(p),k,KToP(k))
        }
    }
}

练习 2.3: 重写PopCount函数,用一个循环代替单一的表达式。比较两个版本的性能。(11.4节将展示如何系统地比较两个不同实现的性能。

package popcount

// pc[i] is the population count of i.
var pc [256]byte

func init() {
    for i := range pc {
        pc[i] = pc[i/2] + byte(i&1)
    }
}

// PopCount returns the population count (number of set bits) of x.
func PopCount(x uint64) int {
    return int(pc[byte(x>>(0*8))] +
        pc[byte(x>>(1*8))] +
        pc[byte(x>>(2*8))] +
        pc[byte(x>>(3*8))] +
        pc[byte(x>>(4*8))] +
        pc[byte(x>>(5*8))] +
        pc[byte(x>>(6*8))] +
        pc[byte(x>>(7*8))])
}

func PopCountByLoop(x uint64) int {
    n := 0
    for i := byte(0); i < 8; i++ {
        n += int(pc[byte(x >>(i*8))])
    }
    return n
}


package popcount

import (
    "testing"
    "reflect"
)

func assert(t *testing.T,expected,actual interface{}){
    if !reflect.DeepEqual(expected,actual){
        t.Errorf("(expected,actual) = (%v,%v)\n",expected,actual)
    }
}

func TestPopCount(t *testing.T) {
    assert(t,32,PopCount(0x1234567890ABCDEF))
}


func TestPopCountByLoop(t *testing.T) {
    assert(t, 32, PopCountByLoop(0x1234567890ABCDEF))
}

func BenchmarkPopCount(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCount(0x1234567890ABCDEF)
    }
}

func BenchmarkPopCountByLoop(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCountByLoop(0x1234567890ABCDEF)
    }
}

练习 2.4: 用移位算法重写PopCount函数,每次测试最右边的1bit,然后统计总数。比较和查表算法的性能差异。

package popcount

// pc[i] is the population count of i.
var pc [256]byte

func init() {
    for i := range pc {
        pc[i] = pc[i/2] + byte(i&1)
    }
}

// PopCount returns the population count (number of set bits) of x.
func PopCount(x uint64) int {
    return int(pc[byte(x>>(0*8))] +
        pc[byte(x>>(1*8))] +
        pc[byte(x>>(2*8))] +
        pc[byte(x>>(3*8))] +
        pc[byte(x>>(4*8))] +
        pc[byte(x>>(5*8))] +
        pc[byte(x>>(6*8))] +
        pc[byte(x>>(7*8))])
}

func PopCountByBitShift(x uint64) int {
    n := 0
    for i := uint(0); i < 64; i++ {
        if (x>>i)&1 != 0 {
            n++
        }
    }
    return n
}

package popcount

import (
    "reflect"
    "testing"
)

func assert(t *testing.T, expected, actual interface{}) {
    if !reflect.DeepEqual(expected, actual) {
        t.Errorf("(expected, actual) = (%v, %v)\n", expected, actual)
    }
}

func TestPopCount(t *testing.T) {
    assert(t, 32, PopCount(0x1234567890ABCDEF))
}

func TestPopCountByBitShift(t *testing.T) {
    assert(t, 32, PopCountByBitShift(0x1234567890ABCDEF))
}

func BenchmarkPopCount(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCount(0x1234567890ABCDEF)
    }
}

func BenchmarkPopCountByBitShift(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCountByBitShift(0x1234567890ABCDEF)
    }
}

练习 2.5: 表达式x&(x-1)用于将x的最低的一个非零的bit位清零。使用这个算法重写PopCount函数,然后比较性能。

package popcount

// pc[i] is the population count of i.
var pc [256]byte

func init() {
    for i := range pc {
        pc[i] = pc[i/2] + byte(i&1)
    }
}

// PopCount returns the population count (number of set bits) of x.
func PopCount(x uint64) int {
    return int(pc[byte(x>>(0*8))] +
        pc[byte(x>>(1*8))] +
        pc[byte(x>>(2*8))] +
        pc[byte(x>>(3*8))] +
        pc[byte(x>>(4*8))] +
        pc[byte(x>>(5*8))] +
        pc[byte(x>>(6*8))] +
        pc[byte(x>>(7*8))])
}

func PopCountByBitClear(x uint64) int {
    n := 0
    for x != 0 {
        x = x & (x - 1)
        n++
    }
    return n
}

package popcount

import (
    "reflect"
    "testing"
)

func assert(t *testing.T, expected, actual interface{}) {
    if !reflect.DeepEqual(expected, actual) {
        t.Errorf("(expected, actual) = (%v, %v)\n", expected, actual)
    }
}

func TestPopCount(t *testing.T) {
    assert(t, 32, PopCount(0x1234567890ABCDEF))
}

func TestPopCountByBitClear(t *testing.T) {
    assert(t, 32, PopCountByBitClear(0x1234567890ABCDEF))
}

func BenchmarkPopCount(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCount(0x1234567890ABCDEF)
    }
}

func BenchmarkPopCountByBitClear(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCountByBitClear(0x1234567890ABCDEF)
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Go语言圣经》是一本广受好评的教材,旨在帮助读者系统地学习和掌握Go语言。这本书以简明清晰的方式介绍了Go语言的各种特性、语法和用法,是入门和进阶者的理想选择。 首先,该书提供了对Go语言基础知识的全面介绍。它从简单到复杂地解释了Go语言的基本概念,诸如变量、函数、循环和条件语句等等。通过丰富的例子和练习,读者能够逐步理解和掌握这些概念。 其次,该书详细介绍了Go语言的高级特性和用法。读者可以学习到Go语言的面向对象编程、并发编程、网络编程等关键技术。并发编程是Go语言的一个独特特性,对于提高程序性能和扩展能力非常重要。 此外,该书还包含了对常见问题和陷阱的讲解,帮助读者避免一些常见的错误和陷阱。同时,书中提供了大量的案例和实践项目,读者可以通过实际操作来巩固所学内容。 《Go语言圣经》以其简洁明了的风格和对细节的深入讲解而闻名。无论是作为初学者的入门指南,还是作为有经验的开发者的参考书,这本书都能满足读者的需求。此外,该书的PDF版本能够方便地在线或离线阅读,为读者提供了更加便捷的学习体验。 综上所述,《Go语言圣经》是一本内容丰富、权威性强的优秀教材。它不仅适合Go语言的初学者,也适用于那些想要深入学习和掌握Go语言的开发者。无论是在线阅读还是PDF版本,读者都能够方便地获取和利用这本宝贵的学习资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DreamCatcher

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值