Programming Fundamentals/Conditions/Go

From Wikiversity
Jump to navigation Jump to search

conditions.go[edit | edit source]

// This program asks the user to select Fahrenheit or Celsius conversion
// and input a given temperature. Then the program converts the given 
// temperature and displays the result.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://golang.org/doc/

package main

import "fmt"

func main() {
    var choice = GetChoice()

    if choice == "C" || choice == "c" {
        var temperature = GetTemperature("Fahrenheit")
        var result = CalculateCelsius(temperature)
        DisplayResult(temperature, "Fahrenheit", result, "Celsius")
    } else if choice == "F" || choice == "f" {
        var temperature = GetTemperature("Celsius")
        var result = CalculateFahrenheit(temperature)
        DisplayResult(temperature, "Celsius", result, "Fahrenheit")
    } else {
        fmt.Printf("You must enter C to convert to Celsius or F to convert to Fahrenheit.")
    }
}

func GetChoice() string {
    var choice string

    fmt.Printf("Enter C to convert to Celsius or F to convert to Fahrenheit: ")
    fmt.Scanln(&choice)
    return choice
}

func GetTemperature(label string) float32 {
    var temperature float32
    
    fmt.Printf("Enter %s temperature: ", label)
    fmt.Scanln(&temperature)
    return temperature
}

func CalculateCelsius(fahrenheit float32) float32 {
    var celsius = (fahrenheit - 32) * 5 / 9
    return celsius
}

func CalculateFahrenheit(celsius float32) float32 {
    var fahrenheit = celsius * 9 / 5 + 32
    return fahrenheit
}

func DisplayResult(
    temperature float32,
    fromLabel string,
    result float32,
    toLabel string) {
    fmt.Printf("%f° %s is %f° %s\n", temperature, fromLabel, result, toLabel)
}

Try It[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own Go compiler / interpreter / IDE.

See Also[edit | edit source]