2014-11-21 89 views
2

請檢查我的代碼:PHP數學隨機數計算

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

請幫助我。

回答

-3

您應該使用+運算符而不是。運營商。這個。只是將它們粘貼在一起,就好像這些值是字符串一樣。

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

不錯的答案。謝謝@AndreaFaulds :) – Developer 2014-11-21 12:13:41

+1

但2 + 1 * 3結果將2 + 3 = 3 * 3 => 9?但5預計 – MouradK 2014-11-21 14:02:58

+0

@MouradK你是對的。我得到錯誤輸出數學:3 - 5 * 5 = -22但輸出是= -10。這不是一個正確的答案。 – Developer 2014-11-21 14:49:19

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 syntaxPHP 5.4+版本要求。

+0

解析錯誤:語法錯誤,意外的'['在第2行E:\ xampp \ htdocs \ test \ test.php – Developer 2014-11-21 14:52:04

+0

@chatfun它的語法糖在PHP 5.4中添加:http://php.net/manual/en/language.types.array.php – 2014-11-21 16:10:40

+0

@KevinHerrera此代碼無法正常工作。你能改變你的答案嗎? – Developer 2014-11-21 19:08:38