Compute arithmetic and integer division
Compute arithmetic and integer division
Use +, -, *, / and % for addition, subtraction, multiplication, division and integer remainder. With integer operands, division truncates toward zero. The remainder keeps the sign of the dividend when nonzero. Use a floating-point operand pair when a fractional quotient is needed.
package main
import "fmt"
func main() { items := 17 boxes := 5 fmt.Println(items/boxes, items%boxes) fmt.Println(items+boxes, items-boxes, items*boxes)}Three full boxes contain five items each, with two left over. The second line shows the sum, difference and product. For integer division, x = (x/y)*y + x%y when y is nonzero (using Go integer arithmetic).
Keep the fractional part
package main
import "fmt"
func main() { x := -17 y := 5 fmt.Println(x/y, x%y) fmt.Println(float64(x) / float64(y))}Converting after integer division is too late: float64(17/5) is 3, not 3.4. Convert before dividing. % requires integers. Integer division by a runtime zero panics; a constant zero divisor is rejected at compile time. Check the divisor before dividing (branching is taught next).
Try it locally
Use 29 items and a box capacity of 6. Print full boxes and leftover items, then the floating-point quotient using a different pair: 15 and 4. Expected lines: 4 5 and 3.75.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Expressions and Arithmetic 01: Compute arithmetic and integer division
Check the lesson objective before moving on.
What is -17 / 5 using integer division?
Which expression evaluates to 3.5?