In this exercise, you will create an interactive calculator in Go that allows the user to input two numbers, select an arithmetic operation ("+", "-", "*", "/"), and print the result. You will practice user input handling, functions, conditional structures, and loops in Go.
Create a Go program that :
fmt.Print()
to display a message asking the user for input.fmt.Scan()
to capture the userβs input as a string.
// getNumber asks the user to enter a number and returns it
func getNumber(prompt string) float64 {
var input string
for {
fmt.Print(prompt)
fmt.Scan(&input)
num, err := strconv.ParseFloat(input, 64)
if err == nil {
return num
}
fmt.Println("Error: Please enter a valid number.")
}
}
The getOperator function is responsible for retrieving and validating the arithmetic operator from the user. It ensures that only one of the allowed operations (+, -, *, /) is accepted before proceeding with the calculation.
fmt.Scan()
.
// getOperator asks the user for an operation and validates it
func getOperator() string {
var op string
for {
fmt.Print("Choose an operation (+, -, *, /): ")
fmt.Scan(&op)
switch op {
case "+", "-", "*", "/":
return op
default:
fmt.Println("Error: Invalid operation. Try again.")
}
}
}
The calculate
function is responsible for performing the mathematical operation based on the operator provided by the user.
It takes two numbers (num1 and num2) and an operator (op),
then returns the result along with an error if something goes wrong (like division by zero).
// calculate performs the calculation based on the operator
func calculate(num1 float64, op string, num2 float64) (float64, error) {
switch op {
case "+":
return num1 + num2, nil
case "-":
return num1 - num2, nil
case "*":
return num1 * num2, nil
case "/":
if num2 == 0 {
return 0, fmt.Errorf("Error: Division by zero")
}
return num1 / num2, nil
}
return 0, fmt.Errorf("Error: Unknown operation")
}
The main()
function serves as the entry point of the program.
Its role is to orchestrate the entire process by calling other functions in a structured way.
getNumber()
to retrieve the first number.getOperator()
to retrieve the operation.getNumber()
again to retrieve the second number.calculate()
to perform the computation.calculate()
: If calculate()
returns an error (e.g., division by zero), display the error message instead of a result.
// main: main loop of the program
func main() {
fmt.Println("----- Welcome to the Go Calculator -----")
for {
// Read user input
num1 := getNumber("Enter the first number: ")
operator := getOperator()
num2 := getNumber("Enter the second number: ")
// Perform the calculation
result, err := calculate(num1, operator, num2)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("Result: %.2f %s %.2f = %.2f\n", num1, operator, num2, result)
}
// Ask if the user wants to continue
var response string
fmt.Print("Do you want to perform another calculation? (yes/no): ")
fmt.Scan(&response)
if response != "yes" {
fmt.Println("Thank you for using the calculator! See you soon.")
break
}
}
}
package main
import (
"fmt"
"strconv"
)
// getNumber asks the user to enter a number and returns it
func getNumber(prompt string) float64 {
var input string
for {
fmt.Print(prompt)
fmt.Scan(&input)
num, err := strconv.ParseFloat(input, 64)
if err == nil {
return num
}
fmt.Println("Error: Please enter a valid number.")
}
}
// getOperator asks the user for an operation and validates it
func getOperator() string {
var op string
for {
fmt.Print("Choose an operation (+, -, *, /): ")
fmt.Scan(&op)
switch op {
case "+", "-", "*", "/":
return op
default:
fmt.Println("Error: Invalid operation. Try again.")
}
}
}
// calculate performs the calculation based on the operator
func calculate(num1 float64, op string, num2 float64) (float64, error) {
switch op {
case "+":
return num1 + num2, nil
case "-":
return num1 - num2, nil
case "*":
return num1 * num2, nil
case "/":
if num2 == 0 {
return 0, fmt.Errorf("Error: Division by zero")
}
return num1 / num2, nil
}
return 0, fmt.Errorf("Error: Unknown operation")
}
// main: main loop of the program
func main() {
fmt.Println("----- Welcome to the Go Calculator -----")
for {
// Read user input
num1 := getNumber("Enter the first number: ")
operator := getOperator()
num2 := getNumber("Enter the second number: ")
// Perform the calculation
result, err := calculate(num1, operator, num2)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("Result: %.2f %s %.2f = %.2f\n", num1, operator, num2, result)
}
// Ask if the user wants to continue
var response string
fmt.Print("Do you want to perform another calculation? (yes/no): ")
fmt.Scan(&response)
if response != "yes" {
fmt.Println("Thank you for using the calculator! See you soon.")
break
}
}
}
Congratulations! π By completing this exercise, you have built a fully functional interactive calculator in Go, while applying key programming principles like functions, loops, error handling, and user input validation. This project is a solid foundation for more complex Go applications. π
π Thank you for reading these articles! If you find this content valuable and want to support my work, a coffee would be greatly appreciated! βπ
π» I am a freelance web developer, and I personally create and maintain this website. Any support would help me improve and expand it further! π