Skip to content

Instantly share code, notes, and snippets.

@pavarotti305
Created November 5, 2015 15:03
Show Gist options
  • Save pavarotti305/f14bf707f118084e7449 to your computer and use it in GitHub Desktop.
Save pavarotti305/f14bf707f118084e7449 to your computer and use it in GitHub Desktop.
Random_Operation_Math
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title>RandomCalcul</title>
</head>
<body>
<?php
// generation random number between 0 and 999 and the math operator
$nbr = 0;
$result = 0;
for ($i = 0; $i < 4; $i++) {
$nb = rand(0, 999);
$op = rand(0, 2);
switch ($op) {
case 0:
$op = '+';
break;
case 1:
$op = '-';
break;
case 2:
$op = '*';
break;
}
if ($i != 3) {
echo $nb . ' ' . $op;
$result += $nb;
} else {
echo $nb;
$result += $nb;
}
}
echo '<br> The result is : '.$result;
?>
</body>
</html>
@rdoursenaud
Copy link

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
    <meta charset="UTF-8">
    <title>RandomCalcul</title>
</head>
<body>
<?php
$nb = 0; // Seed
$op = ''; // Operator
$formula = ''; // Formula
$result = 0; // Result
for ($i = 0; $i < 4; $i++) {
    // Generate a random seed
    $nb = rand(0, 999);
   // Generate a random operator
    $op = rand(0, 3);
    switch ($op) {
        case 0:
            $op = '+';
            break;
        case 1:
            $op = '-';
            break;
        case 2:
            $op = '*';
            break;
       case 3:
            $op = '/';
            break;
    }
    // Build the formula
    if ($i != 3) {
        $formula .= $nb . ' ' . $op;
    } else {
        $formula .= $nb;
    }
}
// Compute the result
eval ('$result = ' . $formula . ';');
// Display the formula
echo $formula,
    '<br>';
// And the result
echo 'The result should be: ',
    $result,
   '<br>';
?>
</body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment