go · level 1 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Go is a very fast calculator.
Go does maths with operators: + adds, - takes away, * multiplies and / divides. Brackets go first, then * and /, then + and -, like at school.
Careful with /. Divide one int by another and you get a whole number: 7 / 2 is 3, and the half is thrown away. To keep it, use a float64, like 7.0 / 2, which is 3.5.
% gives the , what is left after sharing out. Share 7 sweets between 2 friends: each gets 7 / 2, which is 3, and 7 % 2, which is 1, is left over.
package main
import "fmt"
func main() {
sweets := 7
friends := 2
fmt.Println("Each friend gets", sweets/friends)
fmt.Println("Left over:", sweets%friends)
fmt.Println("Pizza each:", 3.0/2)
} Go will not mix an int and a float64 in one sum, so keep your boxes the same type.
guess first
Ten pizzas, four people. How many each?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
pizzas := 10
people := 4
fmt.Println(pizzas / people)
}
your turn
Your turn. Work out the ice cream bill.
Choose a price for one ice cream and how many you want, both as whole numbers. Then press run to see the bill.
output
press run to see what happens
fix it
The average score is too big. Fix it!
output
press run to see what happens
- 8 and 6 should average 7, but Go says 11. Which part of the sum happens first?
- Go divides before it adds, so only second gets divided by 2.
- Put brackets round first+second so the adding happens first: (first+second)/2. Then press run.
nailed it
you turned go into a calculator. :D
+,-,*and/do maths. Brackets go first.- Dividing one
intby another gives a whole number. %gives the remainder left over after sharing.
new words in your collection
- operator
- remainder
This lesson isn’t saved. A free account remembers every lesson you finish.