Skip to content

Instantly share code, notes, and snippets.

@jawira
Created January 21, 2018 09:29
Show Gist options
  • Save jawira/9270fae41b0c77aea5b2b48746dfce97 to your computer and use it in GitHub Desktop.
Save jawira/9270fae41b0c77aea5b2b48746dfce97 to your computer and use it in GitHub Desktop.
Prints basic multiplication and division, answer is introduced by user.
#!/usr/bin/env php
<?php
declare(strict_types=1);
try {
assert_options(ASSERT_ACTIVE, true);
assert_options(ASSERT_BAIL, true);
main();
} catch (Exception $e) {
die($e->getMessage());
}
/**
* Prints basic multiplication and division, answer is introduced by user.
*
* Example:
*
* ```bash
* $ ./math.php
* 49 ÷ 7 = 7
* 42 ÷ 6 = 7
* 8 × 2 = 16
* 6 × 2 = 12
* 10 × 5 =
* ```
*
* To enable assertion set the following in `php.ini`:
*
* ```ini
* zend.assertions = 1
* ```
*
* @param int $exercises Number of exercises to solve, must be positive
*
* @throws \Exception
*/
function main(int $exercises = 20): void
{
assert($exercises > 0);
while ($exercises--) {
$operation = ['÷', '×'][random_int(0, 1)];
$number1 = random_int(1, 10);
$number2 = random_int(1, 10);
$expected = $number1 * $number2;
if ('÷' === $operation) {
$expected = $number1;
$number1 *= $number2;
}
do {
printf('%s %s %s = ', $number1, $operation, $number2);
$input = (int)trim(fgets(STDIN));
} while ($input !== $expected);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment