Home >Backend Development >PHP Tutorial >Custom range, custom operator, custom number of operations_PHP tutorial

Custom range, custom operator, custom number of operations_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:16:26871browse

<?php

/**
 * 
 * 出题引擎一枚
 *
 * @author Tourmaline
 * @copyright (c) 2013, Unary Inc.
 */
class QuestionEngine {

    /**
     * 出题范围
     * @var string $scope
     */
    public $scope = array(1, 100);

    /**
     * 包含的运算符,含有多个则混合出题
     * @var string $operators 
     */
    public $operators = '+-';

    /**
     * 运算次数
     * @var int 
     */
    public $optTimes = 1;

    public function generate() {
        //按运算次数产生一组数值
        start:
        for ($index = 0; $index < $this->optTimes + 1; $index++) {
            $elements[] = $this->randomValue();
        }
        $operatorType = strlen($this->operators); //有几个运算符供选择
        //开始组装算式
        $question = '';
        for ($index = 0; $index < count($elements); $index++) {
            $question.=' ' . $elements[$index] . ' '; //放一个数字进来
            if ($index < count($elements) - 1)//如果不是最后一个数字的话,在后面加个运算符
                $question.=substr($this->operators, mt_rand(0, $operatorType - 1), 1);
        }

        eval('$anwser = ' . $question . ';');
        if ($anwser < 0) {  //排除结果为负数的情况
            $elements = array();
            goto start;     //需PHP5.3的支持
        }

        echo "$question= " . $anwser;
    }

    /**
     * 产生一个范围内的随机值
     * 
     * @return int
     */
    protected function randomValue() {
        return mt_rand($this->scope[0], $this->scope[1]);
    }

}

测试

 

<?php

include 'QuestionEngine.class.php';
$hello = new QuestionEngine();
$hello->generate();
?>

结果:26 + 85 = 111

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/440112.htmlTechArticle?php/*** * A question generation engine * * @author Tourmaline * @copyright (c) 2013, Unary Inc.*/class QuestionEngine { /*** Question scope * @var string $scope*/ public $scope = array(1,...
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