Heim  >  Artikel  >  Backend-Entwicklung  >  自动化出算术题-拿给儿子练速算吧 o(∩_∩)o

自动化出算术题-拿给儿子练速算吧 o(∩_∩)o

WBOY
WBOYOriginal
2016-07-25 08:49:51962Durchsuche
自定义范围,自定义运算符,自定义运算次数。太牛逼了
  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 optTimes + 1; $index++) {
  28. $elements[] = $this->randomValue();
  29. }
  30. $operatorType = strlen($this->operators); //有几个运算符供选择
  31. //开始组装算式
  32. $question = '';
  33. for ($index = 0; $index $question.=' ' . $elements[$index] . ' '; //放一个数字进来
  34. if ($index $question.=substr($this->operators, mt_rand(0, $operatorType - 1), 1);
  35. }
  36. eval('$anwser = ' . $question . ';');
  37. if ($anwser $elements = array();
  38. goto start; //需PHP5.3的支持
  39. }
  40. echo "$question= " . $anwser;
  41. }
  42. /**
  43. * 产生一个范围内的随机值
  44. *
  45. * @return int
  46. */
  47. protected function randomValue() {
  48. return mt_rand($this->scope[0], $this->scope[1]);
  49. }
  50. }
复制代码
  1. include 'QuestionEngine.class.php';
  2. $hello = new QuestionEngine();
  3. $hello->generate();
  4. ?>
  5. 结果:26 + 85 = 111
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn