-
Notifications
You must be signed in to change notification settings - Fork 795
/
main.go
68 lines (52 loc) · 1.39 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"errors"
"fmt"
"os"
"strings"
)
var originUnit string
var originValue float64
var shouldConvertAgain string
var err error
var errInvalidArguments = errors.New("Invalid arguments")
var errReadingInput = errors.New("Error reading input")
func main() {
if len(os.Args) != 2 {
printError(errInvalidArguments)
}
originUnit = strings.ToUpper(os.Args[1])
for {
fmt.Print("What is the current temperature in " + originUnit + " ? ")
_, err := fmt.Scanln(&originValue)
if err != nil {
printError(errReadingInput)
}
if originUnit == "C" {
convertToFahrenheit(originValue)
} else {
convertToCelsius(originValue)
}
fmt.Print("Would you like to convert another temperature ? (y/n) ")
_, err = fmt.Scanln(&shouldConvertAgain)
if err != nil {
printError(errReadingInput)
}
if strings.ToUpper(strings.TrimSpace(shouldConvertAgain)) != "Y" {
fmt.Println("Good bye!")
break
}
}
}
func printError(err error) {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
func convertToCelsius(value float64) {
convertedValue := (value - 32) * 5 / 9
fmt.Printf("%v F = %.0f C\n", value, convertedValue)
}
func convertToFahrenheit(value float64) {
convertedValue := (value * 9 / 5) + 32
fmt.Printf("%v C = %.0f F\n", value, convertedValue)
}