CodeBlanks Logo Icon CodeBlanks

Project design

Design the calculator skeleton and menu structure.

Project: a calculator

In this project you will write a command-line calculator that does four operations. First design the structure: each operation is a separate function, and hesapla picks the right one by the operator symbol.

func topla(a, b float64) float64
func cikar(a, b float64) float64
func carp(a, b float64) float64
func bol(a, b float64) (float64, error)

func hesapla(a float64, islem string, b float64) (float64, error)

Splitting into small functions makes each piece easy to try on its own.

Why float64?

In a calculator 7 / 2 is expected to give 3.5. That's why numbers are kept as float64. When printing, the %g format hides needless zeros: 3.5 → 3.5, 4.0 → 4.

Practice Skeleton

Write the topla(a, b float64) float64 function and try it with fmt.Printf("%g\n", topla(2, 1.5)).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func topla(a, b float64) float64 { return a + b }

func main() {
    fmt.Printf("%g\n", topla(2, 1.5))
}

Expected output

3.5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why does only the <code>bol</code> function return an <code>error</code>?

  • The others should too
  • It is the only operation that can fail, e.g. division by zero Correct answer
  • Division is slower
  • Go requires an error for division

Explanation: Addition, subtraction and multiplication always give a result; division is undefined at zero and must report it to the caller.

2 Two return values

Question
func bol(a, b float64) (float64, ____) {
Answer
func bol(a, b float64) (float64, error) {

Explanation: Functions that can fail return an error as their last value.

3 Function and role

Term Meaning
topla a + b
bol a / b and an error
hesapla Chooses by operation
%g Hides needless zeros

All lessons in Beginner