Project Simple Calculator
Context
Section titled “Context”Build a command‑line calculator that reads two numbers and an operator (+, -, *, /), then prints the result.
This project combines:
- Reading user input (
bufio,fmt.Scanln) - Type conversion (
strconv.ParseFloat) - Conditional logic (
switch) - Error handling
Step‑by‑step code
Section titled “Step‑by‑step code”package main
import ( "bufio" "fmt" "os" "strconv" "strings")
func main() { reader := bufio.NewReader(os.Stdin)
// Read first number fmt.Print("Enter first number: ") num1Str, _ := reader.ReadString('\n') num1, err1 := strconv.ParseFloat(strings.TrimSpace(num1Str), 64) if err1 != nil { fmt.Println("Invalid number") return }
// Read operator fmt.Print("Enter operator (+, -, *, /): ") op, _ := reader.ReadString('\n') op = strings.TrimSpace(op)
// Read second number fmt.Print("Enter second number: ") num2Str, _ := reader.ReadString('\n') num2, err2 := strconv.ParseFloat(strings.TrimSpace(num2Str), 64) if err2 != nil { fmt.Println("Invalid number") return }
// Perform calculation var result float64 switch op { case "+": result = num1 + num2 case "-": result = num1 - num2 case "*": result = num1 * num2 case "/": if num2 == 0 { fmt.Println("Error: division by zero") return } result = num1 / num2 default: fmt.Println("Invalid operator") return }
fmt.Printf("%g %s %g = %g\n", num1, op, num2, result)}Example interaction
Section titled “Example interaction”Enter first number: 10Enter operator (+, -, *, /): /Enter second number: 310 / 3 = 3.3333333333333335Another example (division by zero)
Section titled “Another example (division by zero)”Enter first number: 5Enter operator (+, -, *, /): /Enter second number: 0Error: division by zero