[英]Creating a multiplication “grid”
I am trying to create a simple multiplication grid in PHP 我正在尝试在PHP中创建一个简单的乘法网格
It should be of the format for example for a 2x2 grid: 它应该是2x2网格的格式:
0 1 2
1 1 2
2 2 4
My issue is getting it to start from 0. 我的问题是让它从0开始。
This is my nested for loop so far: 到目前为止,这是我嵌套的for循环:
for($i=0;$i<=$_POST['rows'];$i++)
{
echo "<tr>";
for($j=0;$j<=$_POST['columns'];$j++)
{
if($i==0)
{
echo "<td>" . 1*$j . "</td>";
}
else
{
$mult = $i * $j;
echo "<td> $mult </td>";
}
}
echo "</tr>";
}
But it gives the output: 但是它给出了输出:
0 1 2
0 1 2
0 2 4
I need the column of 0's to be appropriate. 我需要0的列是适当的。
The way you're getting the top row of 0 1 2 3
is by that special-case on the X-axis. 通过X轴上的特殊情况,您可以获得
0 1 2 3
的第一行。 Do a similar special-case for the Y-axis ( $j
): 对Y轴(
$j
)做类似的特殊情况:
if ($i == 0) {
... 1 * $j ...
}
else if ($j == 0) {
... $i * 1 ...
}
else {
... $i * $j ...
}
You not only have $i==0
as special case but also $j==0
: 您不仅有
$i==0
作为特例,而且还有$j==0
:
if($i==0)
{
echo "<td>" . 1*$j . "</td>";
}
elseif($j==0)
{
echo "<td>" . $i*1 . "</td>";
}
else
{
$mult = $i * $j;
echo "<td> $mult </td>";
}
I don't understand the way you construct your grid. 我不了解您构建网格的方式。 All you need is a row indicator and the number for the multiplication not a nested loop.
您所需要的只是一个行指示符,并且乘法的数字不是嵌套循环。 Second: Why don't you start with 1 instead of catching the case inside the loop.
第二:为什么不从1开始而不是在循环内捕获大小写。 This would be my variant of the multiplication “grid”
这将是我的乘法“网格”的变体
<?php
$rows = $_POST['rows'];
$number = $_POST['columns'];
for( $i=1; $i <= $rows; $i++) {
$mult = $i * $number;
echo "<tr>
<td>" . $i.'*'. $j . "</td>
<td>".$mult."</td>
</tr>";
}
?>
This would to a simple grid (x * y) = result. 这将是一个简单的网格(x * y)=结果。 If you want a complete multiplication table it would be something like this:
如果您想要一个完整的乘法表,它将是这样的:
<?php
$rows = $_POST['rows'];
$number = $_POST['columns'];
echo "<tr><th></th>";
for( $j=1; $j <= $number; $j++) {
echo "<th>".$j."</th>";
}
echo "</tr>";
for( $i=1; $i <= $rows; $i++) {
echo "<tr>";
echo "<th>".$i."</th>";
for( $j=1; $j <= $number; $j++) {
$mult = $i * $j;
echo "<td>".$mult."</td>";
}
echo "</tr>";
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.