Exercise: Temperature Converter in Go (Celsius ↔ Fahrenheit)

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.

Exercise Objectives:

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.

Code Implementation

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'.")
    }
}

Issues and Limitations

  • No error handling for invalid temperature inputs (e.g., letters or symbols).
  • The program crashes if non-numeric input is entered.
  • Does not handle spaces or lowercase variations well.
  • Does not allow repeated conversions without restarting the program.

Enhanced Version with Error Handling

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)
    }
}

Explanation of the Improved Code

The updated version introduces the following enhancements:

  • Importing necessary packages: We use bufio for reading input, strconv for string-to-number conversion, and strings for input cleaning.
  • Error handling: If the user enters a non-numeric temperature, they are prompted to re-enter a valid value.
  • Better user experience: Accepts both "C" and "Celsius" for input, making it more flexible.
  • Prevents program crashes: The loop ensures the user provides correct input before proceeding.

🚀 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! ☕😊


☕ Buy me a coffee