请检查我的代码:
<?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
。
请帮帮我。
答案 0 :(得分: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;
答案 1 :(得分:1)
正如@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);
注意,[]
short array syntax的版本要求为 PHP 5.4 + 。
答案 2 :(得分:-3)
你应该使用+运算符而不是。运营商。的。只需将它粘贴在一起,就像值是字符串一样。