開発環境
- macOS Catalina - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Go (プログラミング言語)
入門Goプログラミング (Nathan Youngman(著)、Roger Peppé(著)、吉川 邦夫(監修, 翻訳)、翔泳社)のUNIT 5(状態と振る舞い)、LESSON 23(組み立てと転送)の練習問題の解答を求めてみる。
コード
package main
import (
"fmt"
"math"
)
type location struct {
name string
lat, long float64
}
func (l location) description() string {
return fmt.Sprintf("%v(緯度%.2f°経度%.2f°)", l.name, l.lat, l.long)
}
type world struct {
radius float64
}
func (w world) distance(l1, l2 location) float64 {
s1, c1 := math.Sincos(rad(l1.lat))
s2, c2 := math.Sincos(rad(l2.lat))
clong := math.Cos(rad(l1.long - l2.long))
return w.radius * math.Acos(s1*s2+c1*c2*clong)
}
func rad(deg float64) float64 {
return deg * math.Pi / 180
}
type gps struct {
current, destination location
world
}
func (g gps) distance() float64 {
return g.world.distance(g.current, g.destination)
}
func (g gps) message() string {
return fmt.Sprintf("現在地: %v\n行き先、%vまで%.2fkm",
g.current.description(), g.destination.description(), g.distance())
}
type rover struct {
gps
}
func (r rover) message() string {
return r.gps.message()
}
func main() {
mars := world{radius: 3389.5}
bradBuryLanding := location{name: "Brad Bury", lat: -4.5895, long: 137.4417}
elysiumPlanita := location{name: "Elysium Planita", lat: 4.5, long: 135.9}
marsGps := gps{
current: bradBuryLanding,
destination: elysiumPlanita,
world: mars,
}
curiosity := rover{gps: marsGps}
fmt.Println(curiosity.message())
}
入出力結果(Zsh、PowerShell、Terminal)
% go run ./gps.go
現在地: Brad Bury(緯度-4.59°経度137.44°)
行き先、Elysium Planita(緯度4.50°経度135.90°)まで545.38km
%
0 コメント:
コメントを投稿