Introduction
The Body Mass Index (BMI) is a measure of body fat based on weight and height.
This program calculates BMI to help individuals understand their health status using a simple formula.
BMI is categorized into various ranges such as underweight, normal weight, overweight, and obesity.
Objective
The objective of this project is to create a console-based BMI calculator that takes user input for weight and height,
calculates BMI, and provides feedback based on BMI categories.
This project introduces basic arithmetic operations, conditionals, and user input handling in Go.
Code
package main
import (
"fmt"
)
// Function to calculate BMI
func calculateBMI(weight, height float64) float64 {
return weight / (height * height)
}
// Function to determine BMI category
func getBMICategory(bmi float64) string {
switch {
case bmi < 18.5: return "Underweight" case bmi >= 18.5 && bmi < 24.9: return "Normal weight" case bmi >= 25 && bmi < 29.9:
return "Overweight"
default:
return "Obesity"
}
}
func main() {
var weight, height float64
fmt.Println("Welcome to the BMI Calculator!")
fmt.Print("Enter your weight in kilograms: ")
fmt.Scanln(&weight)
fmt.Print("Enter your height in meters: ")
fmt.Scanln(&height)
if weight <= 0 || height <= 0 {
fmt.Println("Invalid input. Weight and height must be positive numbers.")
return
}
bmi := calculateBMI(weight, height)
category := getBMICategory(bmi)
fmt.Printf("\nYour BMI is: %.2f\n", bmi)
fmt.Printf("You are classified as: %s\n", category)
}
Explanation
The program structure is as follows:
- Calculate BMI: The
calculateBMI
function takes weight and height as input and calculates BMI using the formula:
BMI = weight / (height * height)
. - BMI Category: The
getBMICategory
function determines the BMI category based on predefined ranges:- Underweight: BMI < 18.5
- Normal weight: 18.5 ≤ BMI < 24.9
- Overweight: 25 ≤ BMI < 29.9
- Obesity: BMI ≥ 30
- Main Function: The main function takes user input for weight and height, validates the input,
calculates BMI, determines the category, and displays the result.
How to Run the Program
- Ensure you have Go installed on your system. You can download it from
Go’s official website. - Save the code in a file named
bmi_calculator.go
. - Open a terminal and navigate to the directory containing the file.
- Run the program with the following command:
go run bmi_calculator.go
- Enter your weight (in kilograms) and height (in meters) when prompted to calculate your BMI.
Copyright © Learn Programming. All rights reserved.