php 在php中循环时的偶数和奇数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27379558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
even and odd numbers while loop in php
提问by sheheryar
I want to make even and odd numbers via while loop like this
我想通过这样的while循环生成偶数和奇数
these are even 2,4,6,8,10
these are odd 1,3,5,7,9
I tried to make it with a for loop:
我试图用 for 循环来实现:
<?php
$end=50;
$even= "Even Numbers Are : ";
$odd="<br /> Odd Numbers Are : ";
for($i=1;$i<=$end;$i++)
{
if($i%2==0)
{
$even.=$i.",";
}else $odd.=$i.",";
}
echo $even.$odd;
?>
回答by Peter
This is how to initiate variable:
这是启动变量的方法:
$i = 0;
This is how to increment variable + 1:
这是增加变量 + 1 的方法:
$i = $i + 1;
// or simply
$i++;
This is how while()
loop works:
这就是while()
循环的工作原理:
while([expression here is true]) {
// do stuff
}
With this knowledge you can try do your homework by yourself.
有了这些知识,您可以尝试自己做功课。
Docs:
文档:
回答by Shaun Moore
Bit late to the party but i'm nice and just had to write it anyway
聚会有点晚了,但我很好,反正还是要写的
<?php
$i=0;
while($i <= 10){
if($i % 2 == 0){
echo $i." - Even, ";
}else{
echo $i." - Odd, ";
}
$i++;
}
?>
Also, in your for
loop, you're not opening the else
but you are closing it.
此外,在您的for
循环中,您不是打开else
而是关闭它。
回答by debasish
class IsOdd
{
public function __construct($x) {
if ($x % 2 != 0) {
echo "this odd number";
} else {
echo "this even number";
}
}
}
$odd = new IsOdd(5);
//output
this even number
回答by Ashutosh Verma
<?php
echo"Ashutosh Verma Branch_IT_9889313834";
echo"<br />";
echo "Even No between 1 to 30 are:--";
echo"<br />";
for ($x=1; $x<=30; $x++)
{
if( $x%2==0)
{
echo $x.", ";
}
}
echo "<br />";
echo "Odd No between 1 to 30 are:--";
echo"<br />";
for ($x=1; $x<=30; $x++)
{
if( $x%2!=0)
{
echo $x.", ";
}
}
?>
---------------------------------------OOTPUT-------------------------------------
Ashutosh Verma Branch_IT_9889313834
Even No between 1 to 30 are:--
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30,
Odd No between 1 to 30 are:--
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29,