如何在php循环中分别计算总数digit/numbers、奇数和偶数
How to count the total digit/numbers, the odd numbers and even numbers respectively in a php loop
我想计算金字塔循环中的总数,我想分别计算所有的奇数和偶数。
我的代码中存在错误计算奇数和偶数的问题。
结果应该是:
Total numbers:
Total odd numbers:
Total Even numbers:
<?php
if (isset($_POST['btnsend'])) {
$oddCount = 0;
$evenCount = 0;
$num = $_POST['number'];
$width = strlen($_POST['number']) + 1;
for ($row = 1; $row <= $num; $row++) {
if ($ % 2 == 0)
$evenCount++;
else
$oddCount++;
echo "<div style='display: flex; justify-content: center; text-align: center;'>";
for ($x = 1; $x <= $row; $x++) {
echo "<div style='width: {$width}ch; background: green;'>$row </div>";
}
echo "</div>";
}
echo "<p>You have {$evenCount} even and {$oddCount} odd numbers</p>";
}
我认为您应该能够自己解决这个问题。这不是一个难题。学习编程就是学习解决问题。如果你一直要求别人解决你的问题,你就不是在学习自己。
话虽这么说,我想你想要的是:
<?php
$userInput = 5;
$oddCount = 0;
$evenCount = 0;
$num = $userInput;
$width = strlen($num) + 1;
for ($row = 1; $row <= $num; $row++) {
if ($row % 2 == 0) {
$evenCount += $row;
} else {
$oddCount += $row;
}
echo "<div style='display: flex; justify-content: center; text-align: center;'>";
for ($x = 1; $x <= $row; $x++) {
echo "<div style='width: {$width}ch; background: green;'>$row </div>";
}
echo "</div>";
}
echo "<p>You have {$evenCount} even and {$oddCount} odd numbers</p>";
我不得不删除 $_POST
因为我没有你的表格。对于 5
这个 returns 的输入:
You have 6 even and 9 odd numbers
将输入更改为 10
,您将得到:
You have 30 even and 25 odd numbers
如你所见,这并不难。
我想计算金字塔循环中的总数,我想分别计算所有的奇数和偶数。 我的代码中存在错误计算奇数和偶数的问题。
结果应该是:
Total numbers:
Total odd numbers:
Total Even numbers:
<?php
if (isset($_POST['btnsend'])) {
$oddCount = 0;
$evenCount = 0;
$num = $_POST['number'];
$width = strlen($_POST['number']) + 1;
for ($row = 1; $row <= $num; $row++) {
if ($ % 2 == 0)
$evenCount++;
else
$oddCount++;
echo "<div style='display: flex; justify-content: center; text-align: center;'>";
for ($x = 1; $x <= $row; $x++) {
echo "<div style='width: {$width}ch; background: green;'>$row </div>";
}
echo "</div>";
}
echo "<p>You have {$evenCount} even and {$oddCount} odd numbers</p>";
}
我认为您应该能够自己解决这个问题。这不是一个难题。学习编程就是学习解决问题。如果你一直要求别人解决你的问题,你就不是在学习自己。
话虽这么说,我想你想要的是:
<?php
$userInput = 5;
$oddCount = 0;
$evenCount = 0;
$num = $userInput;
$width = strlen($num) + 1;
for ($row = 1; $row <= $num; $row++) {
if ($row % 2 == 0) {
$evenCount += $row;
} else {
$oddCount += $row;
}
echo "<div style='display: flex; justify-content: center; text-align: center;'>";
for ($x = 1; $x <= $row; $x++) {
echo "<div style='width: {$width}ch; background: green;'>$row </div>";
}
echo "</div>";
}
echo "<p>You have {$evenCount} even and {$oddCount} odd numbers</p>";
我不得不删除 $_POST
因为我没有你的表格。对于 5
这个 returns 的输入:
You have 6 even and 9 odd numbers
将输入更改为 10
,您将得到:
You have 30 even and 25 odd numbers
如你所见,这并不难。