開発環境
- macOS Catalina - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Go (プログラミング言語)
入門Goプログラミング (Nathan Youngman(著)、Roger Peppé(著)、吉川 邦夫(監修, 翻訳)、翔泳社)のUNIT 3(関数とメソッド)、LESSON 15(チャレンジ:温度テーブル)の解答を求めてみる。
コード
package main
import (
"fmt"
"strings"
)
type celsius float64
type fahrenheit float64
type getCellsFunc func(int) (string, string)
type converFunc func(float64) float64
func (c celsius) fahrenheit() fahrenheit {
return fahrenheit(c)*9/5 + 32
}
func (f fahrenheit) celsius() celsius {
return (celsius(f) - 32) * 5 / 9
}
func drawTable(line, header1, header2, format string, rows int, getCells getCellsFunc) {
fmt.Println(line)
fmt.Printf(format, header1, header2)
fmt.Println(line)
for i := 0; i <= rows; i++ {
cell1, cell2 := getCells(i)
fmt.Printf(format, cell1, cell2)
}
fmt.Println(line)
}
func getTemperatures(convert converFunc) getCellsFunc {
return func(i int) (string, string) {
t1 := float64(-40 + 5*i)
t2 := convert(t1)
s1 := fmt.Sprintf("%.1f", t1)
s2 := fmt.Sprintf("%.1f", t2)
return s1, s2
}
}
func main() {
line := strings.Repeat("=", 23)
format := "| %5s | %5s |\n"
rows := 140 / 5
getCells := getTemperatures(func(t float64) float64 {
return float64(celsius(t).fahrenheit())
})
fmt.Println("摂氏", "華氏")
drawTable(line, "℃", "°F", format, rows, getCells)
fmt.Println("華氏", "摂氏")
getCells = getTemperatures(func(t float64) float64 {
return float64(fahrenheit(t).celsius())
})
drawTable(line, "°F", "℃", format, rows, getCells)
}
入出力結果(Zsh、PowerShell、Terminal)
% go run ./tables.go
摂氏 華氏
=======================
| ℃ | °F |
=======================
| -40.0 | -40.0 |
| -35.0 | -31.0 |
| -30.0 | -22.0 |
| -25.0 | -13.0 |
| -20.0 | -4.0 |
| -15.0 | 5.0 |
| -10.0 | 14.0 |
| -5.0 | 23.0 |
| 0.0 | 32.0 |
| 5.0 | 41.0 |
| 10.0 | 50.0 |
| 15.0 | 59.0 |
| 20.0 | 68.0 |
| 25.0 | 77.0 |
| 30.0 | 86.0 |
| 35.0 | 95.0 |
| 40.0 | 104.0 |
| 45.0 | 113.0 |
| 50.0 | 122.0 |
| 55.0 | 131.0 |
| 60.0 | 140.0 |
| 65.0 | 149.0 |
| 70.0 | 158.0 |
| 75.0 | 167.0 |
| 80.0 | 176.0 |
| 85.0 | 185.0 |
| 90.0 | 194.0 |
| 95.0 | 203.0 |
| 100.0 | 212.0 |
=======================
華氏 摂氏
=======================
| °F | ℃ |
=======================
| -40.0 | -40.0 |
| -35.0 | -37.2 |
| -30.0 | -34.4 |
| -25.0 | -31.7 |
| -20.0 | -28.9 |
| -15.0 | -26.1 |
| -10.0 | -23.3 |
| -5.0 | -20.6 |
| 0.0 | -17.8 |
| 5.0 | -15.0 |
| 10.0 | -12.2 |
| 15.0 | -9.4 |
| 20.0 | -6.7 |
| 25.0 | -3.9 |
| 30.0 | -1.1 |
| 35.0 | 1.7 |
| 40.0 | 4.4 |
| 45.0 | 7.2 |
| 50.0 | 10.0 |
| 55.0 | 12.8 |
| 60.0 | 15.6 |
| 65.0 | 18.3 |
| 70.0 | 21.1 |
| 75.0 | 23.9 |
| 80.0 | 26.7 |
| 85.0 | 29.4 |
| 90.0 | 32.2 |
| 95.0 | 35.0 |
| 100.0 | 37.8 |
=======================
%
0 コメント:
コメントを投稿