Temperature converter

Report a typo

Below you will see a Go program that converts the input temperature from Fahrenheit to Celsius and vice-versa:

package main

import "fmt"

func main() {
    var temperature float64
    var unit string
    fmt.Scanln(&temperature, &unit)

    if unit == "F" {
        temperature = ... // code to transform from "F" to "C" goes here
        fmt.Printf("%.2f C", temperature)
    }

    if unit == "C" {
        temperature = ... // code to transform from "C" to "F" goes here
        fmt.Printf("%.2f F", temperature)
    }
}

  • The formula to convert from Fahrenheit to Celsius is: (temperature32)5/9(temperature - 32) * 5/9
  • The formula to convert from Celsius to Fahrenheit is: (temperature9/5)+32(temperature*9/5) + 32

Your task is to use functional decomposition and create three functions:

  • fahrenheitToCelsius() which converts the temperature from Fahrenheit to Celsius and then prints the converted value;
  • celsiusToFahrenheit() which converts the temperature from Celsius to Fahrenheit and then prints the converted value;
  • convertTemperature() that takes as arguments the temperature and the unit and then calls the correct temperature conversion function using an if statement based on the unit.

Note that for this task, you must not modify or delete any code within the main() function!

Sample Input 1:

42 F

Sample Output 1:

5.56 C

Sample Input 2:

22 C

Sample Output 2:

71.60 F

Sample Input 3:

32 F

Sample Output 3:

0.00 C
Write a program in Go
package main

import "fmt"

// nolint: gomnd // <-- DO NOT delete this comment!
func fahrenheitToCelsius(temperature float64) {
celsius := ?
fmt.Printf("%.2f F", celsius)
}

// nolint: gomnd // <-- DO NOT delete this comment!
func celsiusToFahrenheit(temperature float64) {
fahrenheit := ?
fmt.Printf("%.2f C", fahrenheit)
}

// Create a function convertTemperature() that takes `temperature` and `unit` as arguments
// And then calls the correct function to convert the temperature based on the `unit`
func convertTemperature(? float64, ? string) {
if unit == "F" {
// call the function that converts Fahrenheit to Celsius here!
}

if unit == "?" {
?
}
}

// DO NOT delete or modify the contents of the main() function!
func main() {
var temperature float64
var unit string
fmt.Scanln(&temperature, &unit)

convertTemperature(temperature, unit)
}
___

Create a free account to access the full topic