php 自动化出算术题-拿给儿子练速算吧 o(∩_∩)o
自动化出算术题-拿给儿子练速算吧 o(∩_∩)o lt;?phpinclude #39;QuestionEngine.class.php#39;;$hello = new QuestionEngine();$hello-gt;generate();?gt; 结果:26 + 85 = 111[代码片段(61行)]
<?php
include 'QuestionEngine.class.php';
$hello = new QuestionEngine();
$hello->generate();
?>
结果:26 + 85 = 111
<?php /** * Description of QuestionEngine * 出题引擎一枚 */ 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]); } } //该片段来自于http://outofmemory.cn
- 上一篇:php 网页抓图
- 下一篇:php 仿GD读取bmp函数
精彩图集
精彩文章