如何在php中使用for循环计算表的总和
我使用multi-for-loop创建了一个表,我得到了它的结果,但我希望结果是表的总和,如: 我的代码如下:如何在php中使用for循环计算表的总和,php,Php,我使用multi-for-loop创建了一个表,我得到了它的结果,但我希望结果是表的总和,如: 我的代码如下: for($i=1; $i<=2; $i++) { for($j=1; $j<=3; $j++) { echo "<tr>"; $total = $i*$j; $sum = $total+$j; echo "<td>$i * $j = ".$total."</
for($i=1; $i<=2; $i++)
{
for($j=1; $j<=3; $j++)
{
echo "<tr>";
$total = $i*$j;
$sum = $total+$j;
echo "<td>$i * $j = ".$total."</td>";
}
echo "</tr>" ;
echo "<br/>" ;
}
但我想让结果得到相乘的值,比如:
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3 1+2+3 = 6
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6 2+4+6 = 12
如果有人知道这个答案,我将不胜感激。您需要将每个循环的总数相加
for($i=1; $i<=2; $i++)
{
$sum =0; // initiate sum variable with 0
for($j=1; $j<=3; $j++)
{
$total = $i*$j;
$sum += $total; // add total value to sum
echo "$i * $j = ".$total."\n";
}
echo "Sum = $sum\n" ; // echo sum value
}
首先,你必须做算术题。 在2d循环结束时,进行回波。 您在$sum=$total+$j;它是:$sum=$total+$sum
for($i=1; $i<=2; $i++)
{
$sum = 0;
for($j=1; $j<=3; $j++)
{
echo "<tr>";
$total = $i*$j;
$sum = $total+$sum;
echo "<td>$i * $j = ".$total."</td>";
}
echo "</tr>" ;
echo "<tr><td>SUM : ".$sum."</td></tr>";
echo "<br/>" ;
对于($i=1;$i对于($i=1;$i请尝试此
echo "<table>";
for($i=1; $i<=2; $i++)
{
$sum =0;
$str = "";
for($j=1; $j<=3; $j++)
{
echo "<tr>";
$total = $i*$j;
$sum = $total+$sum;
echo "<td>$i * $j = ".$total."</td></tr>";
$str = "$str $total +";
}
echo "<tr><td>".substr($str,0, strlen($str)-1)." = $sum</td></tr>" ;
echo "<br/>" ;
}
echo "</table>";
echo”“;
对于($i=1;$i)在您最初的尝试中,您没有尝试将每次乘法的结果相加。您似乎做得很好。只需将循环中的最后一步相加。非常感谢Ravinder Reddy先生。您的计算非常完美,我非常感谢。
for($i=1; $i<=2; $i++)
{
$sum = 0;
for($j=1; $j<=3; $j++)
{
echo "<tr>";
$total = $i*$j;
$sum = $total+$sum;
echo "<td>$i * $j = ".$total."</td>";
}
echo "</tr>" ;
echo "<tr><td>SUM : ".$sum."</td></tr>";
echo "<br/>" ;
for($i=1; $i<=2; $i++)
{
$k ='';
$result ='0';
for($j=1; $j<=3; $j++)
{
echo "<tr>";
$total = $i*$j;
$sum = $total+$j;
echo "<td>$i * $j = ".$total."</td>";
$result += $total;
$k.= " $total + ";
if($j == 3)
{
$k.= " $total";
}
}
echo "<td>" ;
echo "$k = $result";
echo "</td>" ;
echo "</tr>" ;
echo "<br/>" ;
}
echo "<table>";
for($i=1; $i<=2; $i++)
{
$sum =0;
$str = "";
for($j=1; $j<=3; $j++)
{
echo "<tr>";
$total = $i*$j;
$sum = $total+$sum;
echo "<td>$i * $j = ".$total."</td></tr>";
$str = "$str $total +";
}
echo "<tr><td>".substr($str,0, strlen($str)-1)." = $sum</td></tr>" ;
echo "<br/>" ;
}
echo "</table>";