PHP数学随机数计算

Dev*_*per 2 php math

请检查我的代码:

<?php
  $operarors = array( '+', '-', '*' );
  $randOperator = array($operarors[rand(0,2)], $operarors[rand(0,2)]);
  $num1 = rand(0,10);
  $num2 = rand(0,10);
  $num3 = rand(0,10);

  $result = $num1.$randOperator[0].$num2.$randOperator[1].$num3;
  echo "The math: $num1 $randOperator[0] $num2 $randOperator[1] $num3 = $result";
?>
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我没有得到我的结果总数.

假设我得到了3+4*5,输出应该是23,但是它显示了字符串3+4*5.

请帮帮我.

And*_*rea 5

你不能只是连接这样的运算符.我建议做这样的事情:

<?php
function operate($op1, $operator, $op2) {
    switch ($operator) {
        case "+":
            return $op1 + $op2;
        case "-":
            return $op1 - $op2;
        case "*":
            return $op1 * $op2;
    }
}

$operators = array( '+', '-', '*' );

// performs calculations with correct order of operations
function calculate($str) {
    global $operators;

    // we go through each one in order of precedence
    foreach ($operators as $operator) {
        $operands = explode($operator, $str, 2);
        // if there's only one element in the array, then there wasn't that operator in the string
        if (count($operands) > 1) {
            return operate(calculate($operands[0]), $operator, calculate($operands[1]));
        }
    }

    // there weren't any operators in the string, assume it's a number and return it so it can be operated on
    return $str;
}

$randOperator = array($operators[rand(0,2)], $operators[rand(0,2)]);
$num1 = rand(0,10);
$num2 = rand(0,10);
$num3 = rand(0,10);

$str = "$num1 $randOperator[0] $num2 $randOperator[1] $num3";

echo "$str = ", calculate($str), PHP_EOL;
Run Code Online (Sandbox Code Playgroud)