<?php
function generateProblem() {
do {
// 生成第一个数和第一个运算符
$a = mt_rand(1, 15);
$op1 = mt_rand(0, 1); // 0:+, 1:-
// 生成第二个数并验证中间结果
if ($op1 === 0) {
$b_max = min(19 - $a, 10); // 给第三个数留空间
$b = mt_rand(1, $b_max);
$temp = $a + $b;
} else {
$b = mt_rand(1, $a - 1);
$temp = $a - $b;
}
// 生成第二个运算符
$op2 = mt_rand(0, 1);
// 生成第三个数并验证最终结果
if ($op2 === 0) {
$c_max = 20 - $temp;
$c = $c_max > 0 ? mt_rand(1, $c_max) : 0;
$result = $temp + $c;
} else {
$c_max = $temp;
$c = $c_max > 0 ? mt_rand(1, $c_max) : 0;
$result = $temp - $c;
}
} while ($result < 1 || $result > 20); // 确保结果在1-20之间
return [
'problem' => sprintf("%2d %s %2d %s %2d = __",
$a,
$op1 ? '-' : '+',
$b,
$op2 ? '-' : '+',
$c),
'answer' => sprintf("%2d %s %2d %s %2d = %2d",
$a,
$op1 ? '-' : '+',
$b,
$op2 ? '-' : '+',
$c,
$result)
];
}
// 生成100道题
$problems = [];
$answers = [];
for ($i = 0; $i < 100; $i++) {
$data = generateProblem();
$problems[] = $data['problem'];
$answers[] = $data['answer'];
}
// 打印题目
function printBlock($arr) {
echo "<table>";
foreach ($arr as $key=> $row) {
if($key>0 && ($key+1)%5==1){
echo "<tr>";
}
echo "<td style='width: 140px;'>" .$row . "</td>";
if($key>0 && ($key+1)%5==0){
echo "</tr>";
}
}
echo "</table>";
}
echo "========= 20以内三数加减混合题 =========\n\n<br/>";
printBlock($problems);
echo "<br/>\n\n============= 参考答案 ==============\n\n<br/>";
printBlock($answers);
?>