Convert Celsius to Fahrenheit in Go



In this tutorial, we will learn how to convert a temperature from Celsius to Fahrenheit in Go. We will cover the formula used for the conversion and implement it in a Go function.


What is Temperature Conversion

Temperature conversion is the process of changing the temperature value from one unit of measurement to another. The Celsius and Fahrenheit scales are the most commonly used temperature scales. The formula to convert Celsius to Fahrenheit is:

F = C × 9/5 + 32


Syntax

The syntax to convert Celsius to Fahrenheit in Go is:

func celsiusToFahrenheit(celsius float64) float64 {
    return celsius*9/5 + 32
}


Example 1: Converting Celsius to Fahrenheit

We can create a function to convert a given Celsius temperature to Fahrenheit using the conversion formula.

For example,

  1. Define a function named celsiusToFahrenheit that takes one parameter celsius of type float64.
  2. Use the formula celsius * 9/5 + 32 to convert the Celsius temperature to Fahrenheit.
  3. Return the converted Fahrenheit temperature.
  4. In the main function, call the celsiusToFahrenheit function with a sample Celsius value and print the result.

Go Program

package main

import (
    "fmt"
)

func celsiusToFahrenheit(celsius float64) float64 {
    return celsius*9/5 + 32
}

func main() {
    // Convert 25 degrees Celsius to Fahrenheit
    celsius := 25.0
    fahrenheit := celsiusToFahrenheit(celsius)
    fmt.Printf("%.2f degrees Celsius is equal to %.2f degrees Fahrenheit\n", celsius, fahrenheit)
}

Output

25.00 degrees Celsius is equal to 77.00 degrees Fahrenheit