Temperature Converter – Go Program
This Go program converts temperatures between Celsius and Fahrenheit. It includes two functions:
celsiusToFahrenheit(celsius float64) float64
: Converts a temperature from Celsius to Fahrenheit.fahrenheitToCelsius(fahrenheit float64) float64
: Converts a temperature from Fahrenheit to Celsius.
Go Code
// temperature_converter.go
package main
import (
"fmt"
)
// Function to convert Celsius to Fahrenheit
func celsiusToFahrenheit(celsius float64) float64 {
return (celsius * 9 / 5) + 32
}
// Function to convert Fahrenheit to Celsius
func fahrenheitToCelsius(fahrenheit float64) float64 {
return (fahrenheit - 32) * 5 / 9
}
func main() {
// Example usage
celsius := 25.0
fahrenheit := 77.0
fmt.Printf("%.2f°C is equal to %.2f°F\n", celsius, celsiusToFahrenheit(celsius))
fmt.Printf("%.2f°F is equal to %.2f°C\n", fahrenheit, fahrenheitToCelsius(fahrenheit))
}
Explanation
This program consists of the following components:
Functions
- celsiusToFahrenheit(celsius float64) float64: This function takes a temperature in Celsius as input and converts it to Fahrenheit using the formula
(celsius * 9 / 5) + 32
. - fahrenheitToCelsius(fahrenheit float64) float64: This function takes a temperature in Fahrenheit as input and converts it to Celsius using the formula
(fahrenheit - 32) * 5 / 9
.
Main Function
The main
function demonstrates how to use these conversion functions. It initializes two example temperatures, one in Celsius and one in Fahrenheit, and then prints the converted values to the console.