Lesson contents

Go — Constants, variables, and integer arithmetic

In Go, integer division and remainder separate a nonnegative price in cents into whole dollars and leftover cents. A constant can hold a fixed unit price.

A simple example

Change a stored number

  1. Start with n starts at 2
  2. Do this Add 1 to n
  3. Result 3
After the assignment, reading the same variable gives its new value.
main.go
package main

import "fmt"


func main() {
    n := 2
    n++
    fmt.Println(n)
}
Output
3
Advertisements

Calculate a receipt in cents

Go infers the type of quantity from its integer initializer. The untyped constant priceCents participates in the integer calculation. Printf formats a two-digit remainder without converting the calculation to floating point.

Notebooks: 3 × 125¢ = 375¢. Delivery: 50¢. Amount to pay: 425¢.
Check a stationery order

A student buys three notebooks at 125 cents each. Add the 50-cent delivery charge once for the whole order. Keeping the arithmetic in cents makes the total easy to check against the receipt.

Run the example

Go 1.20 or later. Run these commands from the directory containing the example.

go run main.go
main.go
package main

import (
	"fmt"
)

func main() {
	const priceCents = 125
	quantity := 3
	total := priceCents*quantity + 50
	fmt.Printf("%d.%02d\n", total/100, total%100)
}
Output
4.25

Three items at 125 cents cost 375 cents. Adding one 50-cent delivery charge gives 425 cents. The quotient and remainder on division by 100 give 4 dollars and 25 cents.

Try it yourself

What happens if each item costs 101 cents?

Check your answer

Three items plus delivery cost 353 cents, so the output becomes 3.53.

A Tour of Go

Related tags

  • Go
  • integers
  • variables
  • arithmetic