Home >Backend Development >PHP Tutorial >Automatically solve arithmetic problems - give it to your son to practice quick calculations o(∩_∩)o

Automatically solve arithmetic problems - give it to your son to practice quick calculations o(∩_∩)o

WBOY
WBOYOriginal
2016-07-25 08:49:511021browse
Custom range, custom operator, custom number of operations. So cool
  1. /**
  2. * Description of QuestionEngine
  3. * A question engine
  4. *
  5. * @author lyc
  6. * @copyright (c) 2013, Unary Inc.
  7. */
  8. class QuestionEngine {
  9. /**
  10. * Question scope
  11. * @var string $scope
  12. */
  13. public $scope = array(1, 100);
  14. /**
  15. * Operators included, if there are multiple operators, the question will be mixed
  16. * @var string $operators
  17. */
  18. public $operators = '+-';
  19. /**
  20. * Number of operations
  21. * @var int
  22. */
  23. public $optTimes = 1;
  24. public function generate() {
  25. //Generate a set of values ​​​​according to the number of operations
  26. start:
  27. for ($index = 0; $index < $this->optTimes + 1; $index++) {
  28. $elements[] = $this->randomValue();
  29. }
  30. $operatorType = strlen( $this->operators); //There are several operators to choose from
  31. //Start assembling the calculation
  32. $question = '';
  33. for ($index = 0; $index < count($elements); $index++ ) {
  34. $question.=' ' . $elements[$index] . ' '; //Put a number in
  35. if ($index < count($elements) - 1)//If it is not the last number, Add an operator at the end
  36. $question.=substr($this->operators, mt_rand(0, $operatorType - 1), 1);
  37. }
  38. eval('$anwser = ' . $question . '; ');
  39. if ($anwser < 0) { //Exclude the case where the result is a negative number
  40. $elements = array();
  41. goto start; //Requires PHP5.3 support
  42. }
  43. echo "$question= " . $anwser;
  44. }
  45. /**
  46. * Generate a random value within a range
  47. *
  48. * @return int
  49. */
  50. protected function randomValue() {
  51. return mt_rand($this->scope[0], $this->scope[1]);
  52. }
  53. }
Copy code
  1. include 'QuestionEngine.class.php';
  2. $hello = new QuestionEngine();
  3. $hello->generate();
  4. ?>
  5. Result: 26 + 85 = 111
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn