自動化出算術題-拿給兒子練速算吧 o(∩_∩)o

來源:互聯網
上載者:User
自訂範圍,自訂運算子,自訂運算次數。太牛逼了
  1. /**
  2. * Description of QuestionEngine
  3. * 出題引擎一枚
  4. *
  5. * @author lyc
  6. * @copyright (c) 2013, Unary Inc.
  7. */
  8. class QuestionEngine {
  9. /**
  10. * 出題範圍
  11. * @var string $scope
  12. */
  13. public $scope = array(1, 100);
  14. /**
  15. * 包含的運算子,含有多個則混合出題
  16. * @var string $operators
  17. */
  18. public $operators = '+-';
  19. /**
  20. * 運算次數
  21. * @var int
  22. */
  23. public $optTimes = 1;
  24. public function generate() {
  25. //按運算次數產生一組數值
  26. start:
  27. for ($index = 0; $index < $this->optTimes + 1; $index++) {
  28. $elements[] = $this->randomValue();
  29. }
  30. $operatorType = strlen($this->operators); //有幾個運算子供選擇
  31. //開始組裝算式
  32. $question = '';
  33. for ($index = 0; $index < count($elements); $index++) {
  34. $question.=' ' . $elements[$index] . ' '; //放一個數字進來
  35. if ($index < count($elements) - 1)//如果不是最後一個數位話,在後面加個運算子
  36. $question.=substr($this->operators, mt_rand(0, $operatorType - 1), 1);
  37. }
  38. eval('$anwser = ' . $question . ';');
  39. if ($anwser < 0) { //排除結果為負數的情況
  40. $elements = array();
  41. goto start; //需PHP5.3的支援
  42. }
  43. echo "$question= " . $anwser;
  44. }
  45. /**
  46. * 產生一個範圍內的隨機值
  47. *
  48. * @return int
  49. */
  50. protected function randomValue() {
  51. return mt_rand($this->scope[0], $this->scope[1]);
  52. }
  53. }
複製代碼
  1. include 'QuestionEngine.class.php';
  2. $hello = new QuestionEngine();
  3. $hello->generate();
  4. ?>
  5. 結果:26 + 85 = 111
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.