In this guide, we will develop a simple Tip Calculator program in Go. The program will calculate the tip amount based on the bill total and the tip percentage entered by the user. It’s a great way to get started with Go programming!
Objective
The objective of this Tip Calculator program is to create a simple application in Go that takes the total bill amount and tip percentage as inputs and calculates the tip amount. The program will then display the calculated tip as well as the total amount (bill + tip).
Go Program Code
package main
import "fmt"
func main() {
var billTotal float64
var tipPercentage float64
// Ask user for the bill total
fmt.Print("Enter the total bill amount: $")
fmt.Scanln(&billTotal)
// Ask user for the tip percentage
fmt.Print("Enter the tip percentage (e.g., 15 for 15%): ")
fmt.Scanln(&tipPercentage)
// Calculate the tip amount
tipAmount := (billTotal * tipPercentage) / 100
// Calculate the total amount including tip
totalAmount := billTotal + tipAmount
// Display the calculated tip and total amount
fmt.Printf("Tip Amount: $%.2f\n", tipAmount)
fmt.Printf("Total Amount (Bill + Tip): $%.2f\n", totalAmount)
}
Explanation of the Program
The program starts by importing the “fmt” package, which provides functions for input and output in Go.
- Variables: We define two variables –
billTotal
(for the total bill) andtipPercentage
(for the tip percentage). - Input: The program prompts the user to enter the total bill and tip percentage.
- Tip Calculation: The tip amount is calculated using the formula
tipAmount = (billTotal * tipPercentage) / 100
. - Total Calculation: The total amount is the sum of the bill and the calculated tip:
totalAmount = billTotal + tipAmount
. - Output: The program then prints the tip amount and the total amount to the console.
How to Run the Program
To run the Tip Calculator program in Go, follow these steps:
- Ensure that Go is installed on your computer. You can download it from the official Go Downloads Page.
- Save the code in a file with a
.go
extension (e.g.,tip_calculator.go
). - Open a terminal or command prompt and navigate to the directory where the file is saved.
- Run the program by typing
go run tip_calculator.go
in the terminal. - Enter the bill amount and tip percentage as prompted, and the program will display the calculated tip and total amount.