2012-12-09 45 views
1

我有一個網站,需要根據3個參數生成隨機數學問題:運算符(加法,減法,乘法,除法),重新組合(攜帶或不攜帶)和列(一個或二)。我一直在試圖圍繞如何去做這件事,但我提出的一切都有某種缺陷。動態創建數學表達式

這裏是我與目前的工作是什麼:

function create_problem($operator, $regrouping, $columns){ 
    $top = rand(1,9); 
    $bottom = rand(1,9); 

    if($operator == "+"){ 
     if($columns == 1 && $regrouping === false){ 
      $result = array(
       'top' => $top, 
       'bottom' => $bottom, 
       'formula' => "$top.$operator.$bottom" 
      ); 
     } 
     if($columns == 2){ 
      if($regrouping === false){ 
       if($top+$bottom > 9){ 
        $diff = ($top+$bottom)-10; 
        $top = $diff+rand(1, 3);  
       } 
       $result = array(
        'top' => $top, 
        'bottom' => $bottom, 
        'formula' => "$top.$operator.$bottom" 
       ); 
      }else{ 
       if($top+$bottom < 10){ 
        $top = rand(1, $bottom+1); 
       } 
      } 
     } 
    } 
    return $result; 
} 

如果有人已經處理了這一點,或者如果任何人有任何指針,我將非常感激!

回答

2

這個函數首先檢查重組,併產生隨機數,以便共列數小於10(無進位)或大於或等於10(進位)。

function create_problem($operator, $regrouping, $columns){ 
$x1 = ''; 
$x2 = ''; 
$y1 = ''; 
$y2 = ''; 
if ($regrouping){ 
    if ($columns == 2){ 
    $x1 = rand(1,9); 
    $x2 = rand(0,9); 
    $y1 = rand(9-$x1,9); 
    $y2 = rand(10-$x2,9); 
    } else { 
    $x1 = rand(1,9); 
    $y1 = rand(9-$x1,9); 
    } 
} else { 
    if ($columns == 2){ 
    $x1 = rand(1,8); 
    $x2 = rand(0,8); 
    $y1 = rand(1,9-$x1); 
    $y2 = rand(0,9-$x2); 
    } else { 
    $x1 = rand(1,8); 
    $y1 = rand(1,9-$x1); 
    } 
} 

return $x1.$x2.$operator.$y1.$y2; 
} 

前..

..where 3 = $ X1 1 = $ X2 5 = $ Y1 4 = $ Y2

+0

一個簡單的測試運行看起來很不錯,有兩個小問題。 1)'create_problem(「 - 」,false,2);'返回'68-3-5'的輸出而不是兩列表達式。 2)'create_problem(「 - 」,true,2);'返回'67-40'不需要重組。否則看起來很棒! – chaoskreator

+0

現在再次嘗試編輯..第一個錯誤是一個錯字,第二個錯誤是邏輯問題。 –

+0

-1,你似乎忘記了解釋它是什麼以及它爲什麼起作用。代碼轉儲不是答案。 – Charles