Catch the error that PHP throws for a division by zero, so the program keeps running.
What to build
A program that divides pairs of numbers without crashing.
Requirements
- Read n, then n lines with two integers a and b.
- Print
a / b = Q remainder Rusing whole-number division, orerror: division by zerowhen b is 0.
Input
Line 1: n. Then n lines a b.
Output
n lines.
Constraints
1 ≤ n ≤ 30; 0 ≤ a ≤ 10000; 0 ≤ b ≤ 10000.
Example
Input:
3
10 3
8 0
0 5
Output:
10 / 3 = 3 remainder 1
error: division by zero
0 / 5 = 0 remainder 0
Why it works
The error is an exception, so catch handles it for that one line and the loop moves on to the next.
Examples
Example 1 · Input
3 10 3 8 0 0 5
Expected output
10 / 3 = 3 remainder 1 error: division by zero 0 / 5 = 0 remainder 0
Example 2 · Input
1 7 7
Expected output
7 / 7 = 1 remainder 0
Hints
Hint 1
intdiv and % throw DivisionByZeroError when the divisor is 0.
Hint 2
Wrap them in try and catch (DivisionByZeroError $e).
Solution
Show one correct solution (try it yourself first)
<?php
$n = (int) trim(fgets(STDIN));
for ($i = 0; $i < $n; $i++) {
fscanf(STDIN, "%d %d", $a, $b);
try {
$q = intdiv($a, $b);
$r = $a % $b;
echo "$a / $b = $q remainder $r\n";
} catch (DivisionByZeroError $e) {
echo "error: division by zero\n";
}
}