๐ŸŽ“ A1Learner
๐Ÿ”

Go Numbers

Numbers are the values a program counts and measures with. Whole numbers and decimal numbers follow different division rules.

Add subtract multiply

Three lines run the three signs on whole numbers. Each line prints one result.

package main

import "fmt"

func main() {
	fmt.Println(6 + 4)
	fmt.Println(6 - 4)
	fmt.Println(6 * 4)
}

Two kinds of division

Whole-number division drops the decimal part, so 7 / 2 gives 3. Decimal division keeps the part, so 7.0 / 2 gives 3.5.

package main

import "fmt"

func main() {
	fmt.Println(7 / 2)
	fmt.Println(7.0 / 2)
}

Remainder and its sign

The % sign gives what a division leaves behind. The second line shows the sign of the first number in the result.

package main

import "fmt"

func main() {
	fmt.Println(5 % 2)
	fmt.Println(-5 % 2)
}

Multiplication runs first

Multiplication runs before addition here. The expression 2 + 3 * 4 gives 14, not 20.

package main

import "fmt"

func main() {
	fmt.Println(2 + 3*4)
}

Example

package main

import "fmt"

func main() {
	a := 14
	b := 5
	fmt.Println(a + b)
	fmt.Println(a - b)
	fmt.Println(a / b)
	fmt.Println(float64(a) / float64(b))
}

Key points

  • Use + to add two numbers.
  • Use - to subtract one number from another.
  • Use * to multiply two numbers.
  • Division of two whole numbers drops the decimal part.
  • A decimal value in a division keeps the decimal part.
  • The % sign gives the remainder after a division.
  • Multiplication runs before addition in an expression.

In this example, a holds 14 and b holds 5. The sum is 19 and the difference is 9. Whole-number division gives the quotient 2, and float division gives 2.8.

Note

The remainder takes the sign of the first number. A negative first number gives a negative remainder.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What does 7 / 2 print?