Multiply and divide
- Go course
- Beginner
- Lesson 27/90
- 6 min
Add multiply, divide and zero check.
Multiplication and division
Multiplication is as simple as the others. Division, however, must handle dividing by zero: dividing a float64 by zero doesn't error but produces +Inf, which shows the user a meaningless result. So the divisor is checked and an error returned:
func bol(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("sıfıra bölünemez")
}
return a / b, nil
}Checking the error
When calling a function that returns an error, check the error first and only use the result if there is none:
sonuc, err := bol(10, 0)
if err != nil {
fmt.Println("hata:", err)
return
}
fmt.Println(sonuc)This "error first" pattern shows up everywhere in Go.
Practice Safe division
Write the bol(a, b float64) (float64, error) function. Print the result of bol(9, 2) and the error from bol(1, 0) on separate lines.
Starter code
package main
import (
"errors"
"fmt"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"errors"
"fmt"
)
func bol(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("sıfıra bölünemez")
}
return a / b, nil
}
func main() {
s, _ := bol(9, 2)
fmt.Println(s)
_, err := bol(1, 0)
fmt.Println(err)
}Expected output
4.5 sıfıra bölünemez
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>5.0 / 0.0</code> produce in Go?
- A panic
- 0
- A compile error
- +Inf Correct answer
Explanation: Decimal division follows IEEE 754 and gives infinity; dividing an integer by zero panics.
2 Zero check
if b ____ 0 {
return 0, errors.New("sıfıra bölünemez")
}
if b == 0 {
return 0, errors.New("sıfıra bölünemez")
}
Explanation: b == 0 checks whether the divisor is zero.
3 Operation and result
| Term | Meaning |
|---|---|
carp(3, 4) |
12 |
bol(9, 2) |
4.5, nil |
bol(1, 0) |
0, error |
5.0 / 0.0 |
+Inf |