自定义范围,自定义运算符,自定义运算次数_PHP教程

WBOY
Lepaskan: 2016-07-20 11:16:26
asal
798 orang telah melayarinya

<?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]);
    }

}
Salin selepas log masuk

测试

<?php

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

结果:26 + 85 = 111
Salin selepas log masuk

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/440112.htmlTechArticle?php/** * * 出题引擎一枚 * * @author Tourmaline * @copyright (c) 2013, Unary Inc. */class QuestionEngine { /** * 出题范围 * @var string $scope */ public $scope = array(1,...
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!