練習2.1
向tempconv包添加類型、常量和函數用來處理Kelvin絕對溫度的轉換,Kelvin 絕對零度是?273.15°C,Kelvin絕對溫度1K和攝氏度1°C的單位間隔是一樣的。
conv.go
package tempconv
// CToF converts a Celsius temperature to Fahrenheit.
func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }
// FToC converts a Fahrenheit temperature to Celsius.
func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }
func KToC(k Kelvin) Celsius { return Celsius(k + 273.15) }
func CToT(c Celsius) Kelvin { return Kelvin(c + 273.15) }
tempconv.go
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("%g°K", k) }
練習2.2
寫一個通用的單位轉換程序,用類似cf程序的方式從命令行讀取參數,如果缺省的話則是從標準輸入讀取參數,然后做類似Celsius和Fahrenheit的單位轉換,長度單位可以對應英尺和米,重量單位可以對應磅和公斤等。
conv.go:
package lenthconv
func MToF(m Meter) Feet { return Feet(m / 0.3084) }
func FToM(f Feet) Meter { return Meter(f * 0.3084) }
lenthconv:
package lenthconv
import "fmt"
type Meter float64
type Feet float64
func (m Meter) String() string { return fmt.Sprintf("%g m", m) }
func (f Feet) String() string { return fmt.Sprintf("%g ft", f) }
test:
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"gopl.io/ch2/lenthconv"
)
func main() {
if len(os.Args) == 1 {
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
t, err := strconv.ParseFloat(input.Text(), 64)
if err != nil {
fmt.Fprintf(os.Stderr, "cf: %v\n", err)
os.Exit(1)
}
f := lenthconv.Feet(t)
m := lenthconv.Meter(t)
fmt.Printf("%s = %s, %s = %s\n",
f, lenthconv.FToM(f), m, lenthconv.MToF(m))
}
}
for _, arg := range os.Args[1:] {
t, err := strconv.ParseFloat(arg, 64)
if err != nil {
fmt.Fprintf(os.Stderr, "cf: %v\n", err)
os.Exit(1)
}
f := lenthconv.Feet(t)
m := lenthconv.Meter(t)
fmt.Printf("%s = %s, %s = %s\n",
f, lenthconv.FToM(f), m, lenthconv.MToF(m))
}
}
練習2.3
重寫PopCount函數,用一個循環(huán)代替單一的表達式。比較兩個版本的性能。
func PopCount(x uint64) int {
res := 0
for i := 0; i < 8; i++ {
res += int(pc[byte(x>>(i*8))])
}
return res
}
練習2.4
用移位算法重寫PopCount函數,每次測試最右邊的1bit,然后統(tǒng)計總數。比較和查表算法的性能差異。文章來源:http://www.zghlxwxcb.cn/news/detail-674384.html
func PopCount(x uint64) int {
res := 0
for x != 0 {
res += x & 1
x >>= 1
}
return res
}
練習2.5
表達式x&(x-1)用于將x的最低的一個非零的bit位清零。使用這個算法重寫PopCount函數,然后比較性能。文章來源地址http://www.zghlxwxcb.cn/news/detail-674384.html
func PopCount(x uint64) int {
res := 0
for x != 0 {
res++
x &= x - 1
}
return res
}
到了這里,關于GO語言圣經 第二章習題的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!