In this exercise, you'll learn how to create a temperature converter in Go. You'll work with user input, conditionals, and basic math operations.
1. Read user input for a temperature value.
2. Ask the user for the unit (Celsius or Fahrenheit).
3. Convert the temperature to the opposite unit.
4. Display the converted temperature.
Below is the initial implementation of the temperature converter program.
package main
import (
"fmt"
)
func main() {
var temperature float64
var unit string
fmt.Print("Enter the temperature: ")
fmt.Scanln(&temperature)
fmt.Print("Enter the unit (C/F): ")
fmt.Scanln(&unit)
if unit == "C" || unit == "c" {
converted := (temperature * 9 / 5) + 32
fmt.Printf("Converted: %.2f°F\n", converted)
} else if unit == "F" || unit == "f" {
converted := (temperature - 32) * 5 / 9
fmt.Printf("Converted: %.2f°C\n", converted)
} else {
fmt.Println("Error: Invalid unit. Use 'C' or 'F'.")
}
}
The improved version of the program includes proper error handling and makes it more user-friendly.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
var temperature float64
var unit string
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("Enter the temperature: ")
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
temp, err := strconv.ParseFloat(input, 64)
if err != nil {
fmt.Println("Invalid input. Please enter a valid number.")
} else {
temperature = temp
break
}
}
for {
fmt.Print("Enter the unit (C/F or Celsius/Fahrenheit, Q to quit): ")
unit, _ = reader.ReadString('\n')
unit = strings.TrimSpace(strings.ToUpper(unit))
if unit == "C" || unit == "CELSIUS" {
unit = "C"
break
} else if unit == "F" || unit == "FAHRENHEIT" {
unit = "F"
break
} else if unit == "Q" {
fmt.Println("Goodbye! 👋")
return
} else {
fmt.Println("Invalid unit. Please enter 'C' or 'F'.")
}
}
if unit == "C" {
converted := (temperature * 9 / 5) + 32
fmt.Printf("%.2f°C = %.2f°F\n", temperature, converted)
} else {
converted := (temperature - 32) * 5 / 9
fmt.Printf("%.2f°F = %.2f°C\n", temperature, converted)
}
}
The updated version introduces the following enhancements:
bufio
for reading input, strconv
for string-to-number conversion, and strings
for input cleaning.🚀 Thanks for using these exercises! If you find this content helpful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊