A function that can fail returns an error next to its result.
What to build
A program that divides pairs of numbers and reports division by zero as an error.
Requirements
- Write
divide(a, b float64) (float64, error). - Read n, then n lines
a b. For each line printa / b = Rwith R shown with two decimals, orerror: division by zerowhen b is 0. - Print a and b as they are read, without extra zeros (for example
7 / 2 = 3.50).
Input
Line 1: n. Then n lines with two numbers.
Output
n lines.
Constraints
1 ≤ n ≤ 30; a and b are whole numbers between -1000 and 1000.
Example
Input:
3
7 2
5 0
-9 3
Output:
7 / 2 = 3.50
error: division by zero
-9 / 3 = -3.00
Why it works
divide returns the error instead of a wrong number, and main checks it first. The value 0 is never confused with a real answer.
Examples
Example 1 · Input
3 7 2 5 0 -9 3
Expected output
7 / 2 = 3.50 error: division by zero -9 / 3 = -3.00
Example 2 · Input
2 1 3 0 5
Expected output
1 / 3 = 0.33 0 / 5 = 0.00
Hints
Hint 1
Write func divide(a, b float64) (float64, error) and return errors.New("division by zero") when b is 0.
Hint 2
In main, check err != nil before printing the result.
Solution
Show one correct solution (try it yourself first)
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
var n int
fmt.Scan(&n)
for i := 0; i < n; i++ {
var a, b float64
fmt.Scan(&a, &b)
r, err := divide(a, b)
if err != nil {
fmt.Println("error:", err)
continue
}
fmt.Printf("%v / %v = %.2f\n", a, b, r)
}
}