Math That Makes Sense

Math That Makes Sense

Math That Makes Sense

Go does math like you'd expect, with one twist: it won't let you mix types.

Go has all the arithmetic operators:

example.go
sum := 10 + 3    // 13
diff := 10 - 3   // 7
prod := 10 * 3   // 30
quot := 10 / 3   // 3  (not 3.33!)
rem := 10 % 3    // 1

When both numbers are integers, Go uses integer division: it discards the fractional part, so 10 / 3 is 3, not 3.33.

Use decimals when you need the fractional part. A decimal literal like 10.0 is a float64:

example.go
result := 10.0 / 3.0  // 3.3333333333333335

Go won't let you combine two variables of different types, like an int and a float64. You convert the ints with float64() first:

example.go
passed := 47
tests := 50
rate := float64(passed) / float64(tests)  // 0.94

That strictness is deliberate. Go makes you convert types yourself so mixed-type bugs show up at compile time.

>_Exercise

Exercise: Split the Bill

You're splitting a dinner bill. The starter code gives you:

  • total (a float64: 95.50)
  • people (an int: 4)

Calculate each person's share and print the result in this exact format:

example.go
Each person pays: $23.88

%.2f prints the float with two digits after the decimal, so 23.875 shows as 23.88.

Stuck? Reveal a hint to help you.
Hints (0/3)
Key Takeaway
Next UpMaking your code choose between paths.