Introduction
Unit conversion is a common task in various applications, such as engineering, science, and everyday calculations. This program demonstrates how to convert between different units of measurement, including length (meters, kilometers, miles), weight (kilograms, pounds), and volume (liters, gallons). The implementation uses the Go programming language, providing a simple and interactive way to perform these conversions.
Objective
The goal of this program is to create a command-line utility in Go that allows users to convert between different units of length, weight, and volume. The program will accept user input for the source unit, target unit, and value, then compute and display the result.
Code
package main import ( "fmt" "os" ) func main() { fmt.Println("Unit Converter: Length, Weight, Volume") fmt.Println("Select a category:") fmt.Println("1. Length (meters to kilometers, miles)") fmt.Println("2. Weight (kilograms to pounds)") fmt.Println("3. Volume (liters to gallons)") var choice int fmt.Print("Enter your choice (1-3): ") fmt.Scanln(&choice) switch choice { case 1: convertLength() case 2: convertWeight() case 3: convertVolume() default: fmt.Println("Invalid choice. Exiting.") os.Exit(1) } } func convertLength() { fmt.Println("Length Conversion: meters to kilometers, miles") fmt.Print("Enter value in meters: ") var meters float64 fmt.Scanln(&meters) kilometers := meters / 1000 miles := meters / 1609.34 fmt.Printf("%.2f meters is %.2f kilometers or %.2f miles.\n", meters, kilometers, miles) } func convertWeight() { fmt.Println("Weight Conversion: kilograms to pounds") fmt.Print("Enter value in kilograms: ") var kilograms float64 fmt.Scanln(&kilograms) pounds := kilograms * 2.20462 fmt.Printf("%.2f kilograms is %.2f pounds.\n", kilograms, pounds) } func convertVolume() { fmt.Println("Volume Conversion: liters to gallons") fmt.Print("Enter value in liters: ") var liters float64 fmt.Scanln(&liters) gallons := liters * 0.264172 fmt.Printf("%.2f liters is %.2f gallons.\n", liters, gallons) }
Explanation
The program is structured as follows:
- Category Selection: The user is prompted to choose a category: Length, Weight, or Volume.
- Conversion Functions: Each category has a dedicated function (
convertLength
,convertWeight
,convertVolume
) to handle specific unit conversions. - Interactive Input: The user provides input for the value to be converted, and the program calculates the result using predefined formulas.
- Error Handling: Invalid category choices are handled gracefully with an error message and program termination.
How to Run
- Install Go from the official Go website.
- Copy the code into a file named
unit_converter.go
. - Run the program using the command:
go run unit_converter.go
- Follow the on-screen instructions to perform unit conversions.