PHP数学随机数计算


PHP Math random number calculation

请检查我的代码:

<?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";
?>

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

假设我得到3+4*5,输出应该是23,但它显示字符串3+4*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;

正如@AndreaFaulds所说,或者使用回调:(尽管使用 array_reduce 和所有这些数组指针魔术都是不必要的)。

<?php
$ops = [
    '+' => function ($op1, $op2) { return $op1 + $op2; },
    '*' => function ($op1, $op2) { return $op1 * $op2; },
    '-' => function ($op1, $op2) { return $op1 - $op2; }
];
$nums = [rand(0, 10), rand(0, 10), rand(0, 10)];
$operators = [array_rand($ops), array_rand($ops)];
$initial = array_shift($nums);
$result = array_reduce($nums, function ($accumulate, $num) use (&$operators, $ops) {
    return $ops[each($operators)[1]]($accumulate, $num);
}, $initial);

请注意,[]短数组语法的版本要求为 PHP 5.4+

您应该使用 + 运算符而不是 . 运算符。这。只是将其粘贴在一起,就好像值是字符串一样。