<?php function generateMathProblem() { // 随机选择加法或减法 $operation = rand(0, 1) ? '+' : '-'; // 生成两个0到20之间的随机数 $num1 = rand(0, 20); $num2 = rand(0, 20); // 计算结果,注意处理减法可能导致负数的情况 if ($operation == '-') { // 确保减法结果不为负数 if ($num1 < $num2) { // 交换两个数以确保结果为正数 list($num1, $num2) = [$num2, $num1]; } } // 计算结果,如果结果大于20,改为减法 if ($operation == '+') { // 确保减法结果不为负数 if (bcadd($num1,$num2) > 20) { $operation = '-'; if($num2 >= $num1){ // 交换两个数以确保结果为正数 list($num1, $num2) = [$num2, $num1]; } } } // 构建题目字符串 $problem = "$num1 $operation $num2 = "; // 计算结果 $answer = eval("return $num1 $operation $num2;"); return [ 'problem' => $problem, 'answer' => $answer ]; } if ((int)$_GET['timu_num']) { $timu_num = (int)$_GET['timu_num']; } else { $timu_num = 100; } // 生成多少道题目 $problems = []; for ($i = 0; $i < $timu_num; $i++) { $problems[] = generateMathProblem(); } // 输出题目和答案 echo "<table>"; foreach ($problems as $index => $problem) { $num = $index+1; if($num%5 == 1) echo "<tr>"; echo "<td style='width: 120px'>" . $problem['problem'] . "</td>"; if($num%5 == 0) echo "</tr>"; } echo "<tr><td>答案:</td></tr>"; foreach ($problems as $index => $problem) { $num = $index+1; if($num%5 == 1) echo "<tr>"; echo "<td style='width: 120px'>" . "题目 " . $num . ": " . $problem['answer'] . "</td>"; if($num%5 == 0) echo "</tr>"; } echo "</<table>";
标签:题目,num1,num2,timu,echo,num,20,problem,加减法 From: https://www.cnblogs.com/wjs2019/p/18671151