2.1、向tempconv包添加类型、常量和函数用来处理Kelvin绝对温度的转换,Kelvin 绝对零度是−273.15°C,Kelvin绝对温度1K和摄氏度1°C的单位间隔是一样的。
// tempconv.go:
// Package tempconv performs Celsius and Fahrenheit conversions.
package tempconv
import (
"fmt"
)
type Fahrenheit float64
type Celsius 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) }
// conv.go:
// conv
package tempconv
func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }
func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }
func KToC(k Kelvin) Celsius { return Celsius(k - 273.15) }
func CToK(c Celsius) Kelvin { return Kelvin(c + 273.15) }
// convDemo.go
// convDemo
package main
import (
"fmt"
"test/tempconv"
)
func main() {
fmt.Println(tempconv.CToF(tempconv.BoilingC))
fmt.Println(tempconv.CToK(tempconv.BoilingC))
}
运行结果:
$ ./test
212°F
373.15 K
2.2、写一个通用的单位转换程序,用类似cf程序的方式从命令行读取参数,如果缺省的话则是从标准输入读取参数,然后做类似Celsius和Fahrenheit的单位转换,长度单位可以对应英尺和米,重量单位可以对应磅和公斤等。
// unitconv.go:
// Package unitconv performs common unit conversion
package unitconv
import "fmt"
type Meter float64
type Feet float64
type Pound float64
type Kilo float64
func (m Meter) String() string { return fmt.Sprintf("%g m", m) }
func (f Feet) String() string { return fmt.Sprintf("%g ft", f) }
func (p Pound) String() string { return fmt.Sprintf("%g lb", p) }
func (k Kilo) String() string { return fmt.Sprintf("%g kg", k) }
// conv.go:
package unitconv
func FToM(f Feet) Meter { return Meter(f * 0.3048) }
func MToF(m Meter) Feet { return Feet(m / 0.3048) }
func PToK(p Pound) Kilo { return Kilo(p * 0.4535924) }
func KToP(k Kilo) Pound { return Pound(k / 0.4535924) }
// unitconvDemo.go:
// unitconvDemo
package main
import (
"fmt"
"os"
"strconv"
"test/unitconv"
)
func main() {
for _, arg := range os.Args[1:] {
t, err := strconv.ParseFloat(arg, 64)
if err != nil {
fmt.Fprintf(os.Stderr, "unitconv: %v\n", err)
os.Exit(1)
}
m := unitconv.Meter(t)
f := unitconv.Feet(t)
k := unitconv.Kilo(t)
p := unitconv.Pound(t)
fmt.Printf("%s = %s, %s = %s\n", m, unitconv.MToF(m), f, unitconv.FToM(f))
fmt.Printf("%s = %s, %s = %s\n", k, unitconv.KToP(k), p, unitconv.PToK(p))
}
}
运行结果:
$ ./test 10.01
10.01 m = 32.841207349081365 ft, 10.01 ft = 3.051048 m
10.01 kg = 22.067901234567902 lb, 10.01 lb = 4.540536 kg