2020年1月20日月曜日

開発環境

入門Goプログラミング (Nathan Youngman(著)、Roger Peppé(著)、吉川 邦夫(監修, 翻訳)、翔泳社)のUNIT 3(関数とメソッド)、LESSON 13(メソッド)の練習問題の解答を求めてみる。

コード

package main

import "fmt"

type celsius float64
type fahrenheit float64
type kelvin float64

func (c celsius) fahrenheit() fahrenheit {
 return fahrenheit(c)*9/5 + 32
}
func (c celsius) kelvin() kelvin {
 return kelvin(c) + 273.15
}
func (k kelvin) celsius() celsius {
 return celsius(k) - 273.15
}
func (k kelvin) fahrenheit() fahrenheit {
 return k.celsius().fahrenheit()
}
func (f fahrenheit) celsius() celsius {
 return (celsius(f) - 32) * 5 / 9
}
func (f fahrenheit) kelvin() kelvin {
 return f.celsius().kelvin()
}

func main() {
 var (
  c celsius    = 0
  f fahrenheit = 0
  k kelvin     = 0
 )
 fmt.Printf(
  "%.2f℃ ≈ %.2f°F\n%.2[1]f℃ ≈ %.2[3]f°K\n",
  c, c.fahrenheit(), c.kelvin())

 fmt.Printf(
  "%.2f°F ≈ %.2fK\n%.2[1]f°F ≈ %.2[3]f℃\n",
  f, f.kelvin(), f.celsius())

 fmt.Printf(
  "%.2fK ≈ %.2f°F\n%.2[1]fK ≈ %.2[3]f℃\n",
  k, k.fahrenheit(), k.celsius())
}

入出力結果(Zsh、PowerShell、Terminal)

% go run ./method.go 
0.00℃ ≈ 32.00°F
0.00℃ ≈ 273.15°K
0.00°F ≈ 255.37K
0.00°F ≈ -17.78℃
0.00K ≈ -459.67°F
0.00K ≈ -273.15℃
%

0 コメント:

コメントを投稿