Automatically solve arithmetic problems - give it to your son to practice quick calculations o(∩_∩)o
Release: 2016-07-25 08:49:51
Original
1020 people have browsed it
Custom range, custom operator, custom number of operations. So cool
- /**
- * Description of QuestionEngine
- * A question engine
- *
- * @author lyc
- * @copyright (c) 2013, Unary Inc.
- */
- class QuestionEngine {
-
- /**
- * Question scope
- * @var string $scope
- */
- public $scope = array(1, 100);
-
- /**
- * Operators included, if there are multiple operators, the question will be mixed
- * @var string $operators
- */
- public $operators = '+-';
-
- /**
- * Number of operations
- * @var int
- */
- public $optTimes = 1;
-
- public function generate() {
- //Generate a set of values according to the number of operations
- start:
- for ($index = 0; $index < $this->optTimes + 1; $index++) {
- $elements[] = $this->randomValue();
- }
- $operatorType = strlen( $this->operators); //There are several operators to choose from
- //Start assembling the calculation
- $question = '';
- for ($index = 0; $index < count($elements); $index++ ) {
- $question.=' ' . $elements[$index] . ' '; //Put a number in
- if ($index < count($elements) - 1)//If it is not the last number, Add an operator at the end
- $question.=substr($this->operators, mt_rand(0, $operatorType - 1), 1);
- }
-
- eval('$anwser = ' . $question . '; ');
- if ($anwser < 0) { //Exclude the case where the result is a negative number
- $elements = array();
- goto start; //Requires PHP5.3 support
- }
- echo "$question= " . $anwser;
- }
- /**
- * Generate a random value within a range
- *
- * @return int
- */
- protected function randomValue() {
- return mt_rand($this->scope[0], $this->scope[1]);
- }
-
- }
-
Copy code
- include 'QuestionEngine.class.php';
- $hello = new QuestionEngine();
- $hello->generate();
- ?>
-
- Result: 26 + 85 = 111
Copy code
|
Statement of this Website
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
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31