2011-03-18 56 views
1
<?php 

$ohhai = 1; 

while ($ohhai != 102) 
{ 
    for($t = 1; $t < $ohhai; $t++) 
    { 
     //if ($t % 3 == 0) 
     //{ 
      $e = $t/3; 
      if (is_int($e)) 
      { 
       echo "*"; 

      } 
     //} 
    } 

    echo("<br />"); 
    $ohhai++; 
} 

?> 

我试图做的是输出字符串每次第三次,就像这样:每三个时间,打印此

$t = 3; 

* 

$t = 6; 

** 

$t = 9; 

*** 

等。我尝试了很多方法来获得这个,这是最接近我的,而且这是我最接近的。打印出来的东西位于这里(难以输出)。我怎样才能完成每一次第三次的诀窍?

+0

你能告诉确切的代码,在http://appstorecrazy.com/phpstoof/pye/test.php – Chris 2011-03-18 03:40:55

回答

3

/给你商数。取而代之,您需要采取%运算符,并检查%运算的结果是否为然后打印该值。

<?php 

$ohhai = 1; 
$times = 1; // This is variable that keeps track of how many times * needs to printed. It's fairly straight forward to understand, why this variable is needed. 

while ($ohhai != 102) 
{ 
    if ($t % 3 == 0) 
    { 
     for ($counter = 0; $counter < $times; $counter++) 
     { 
      echo "*"; 
     } 
     $times ++; 
     echo("<br />"); 
    } 
    $ohhai++; 
} 

?> 
+0

这是注释掉的代码。与它取消注释,它看起来像这样:http://appstorecrazy.com/phpstoof/pye/test.php – Imnotanerd 2011-03-18 03:26:39

+0

@Imnotanerd - 检查它。我认为那是你需要的。 – Mahesh 2011-03-18 03:36:06

+0

是$ t错误吗?你的意思是美元吗? – Imnotanerd 2011-03-18 03:38:38

2
if($something % 3 == 0) 
{ 
    //do something 
} 

%是模运算符,它返回除法的余数。如果结果为0,则划分发生而没有余数。

+1

这是注释掉的代码。它没有注释,它看起来像这样:http://appstorecrazy.com/phpstoof/pye/test.php – Imnotanerd 2011-03-18 03:22:28

0

可以使用在大多数语言模数运算符,即,除法运算

如果(iterationNumber%3 == 0)这是在第三时间的剩余部分。

+0

这是注释掉的代码。与它未注释,它看起来像这样:http://appstorecrazy.com/phpstoof/pye/test.php – Imnotanerd 2011-03-18 03:25:40

0

我对你想要做什么有点不清楚,但我怀疑正是你缺少的是取模运算,%

在PHP中,x % y的计算结果是将x除以y得到的余数。所以,如果你计算的东西,你要运行的每第三个部分代码,你可以这样做:

if (0 == $count % 3) { // action to perform on every third item }

看到http://php.net/manual/en/language.operators.arithmetic.php PHP手册以获取更多信息。

此外,我认为你可能需要一个循环,以便打印出正确数量的* s。

<?php 

$ohhai = 1; 

while ($ohhai != 102) 
{ 

    // we only want to print on multiples of 3 
    if(0 == $ohhai % 3) { 


    for($t = 1; $t <= $ohhai; $t++){ 
     echo "*"; 
    } 

    echo("<br />\n"); 
    } 
$ohhai++; 
} 
+0

这是注释掉的代码。与它未注释,它看起来像这样:http://appstorecrazy.com/phpstoof/pye/test.php – Imnotanerd 2011-03-18 03:27:29

0

使用模运算符。

例如:

  1. 10 % 2 = 0因为2将10没有余数。
  2. 10 % 3 = 1因为3分10用的1
你注释代码

所以剩余部分,你的脚本应该是这样的:

<?php 

$ohhai = 1; 

while ($ohhai != 102) 
{ 
    for($t = 1; $t < $ohhai; $t++) 
    { 
     if ($t % 3 == 0) 
     { 
      echo "*"; 
     } 
    } 

    echo("<br />"); 
    $ohhai++; 
} 

?> 
0
$total=102; 
for($i=1;$i<=$total;$i++) { 
    if($i%3==0){ 
     for($j=1;$j<=($i/3);$j++) 
      echo "*"; 
     echo "<br/>"; 
    } 
}