2011-03-18 40 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/>"; 
    } 
}