2016-05-29 69 views
-3

我想使用PHP做while循環並找到一個隨機數。嘗試使用PHP'do-while'循環來查找隨機數

下面是代碼,它不工作...

<?php 

$start = 10; 
$end = 1; 
$find = rand(0,9); 

do { 
if ($start == $find): 
    echo "Found!"; 
elseif ($start != $find): 
    echo $start; 
    $start = $start - $end; 
endif; 
} while ($start != $find); 

?> 

回答

0

在最後的迭代,$start = $start - $end;$start變量等於$find時,你立刻跳出循環的(因爲while ($start != $find);false在那一刻)。這就是說,

if ($start == $find): 
    echo "Found!"; 

永遠不會發生。如果你明白這一點,那麼你明白,始終驗證出循環$start == $find。所以,你可以在底部移動這段代碼:

$start = 10; 
$end = 1; 
$find = rand(0,9); 

do { 
    if ($start != $find): // ALWAYS true, can be omitted 
     echo $start; 
     $start = $start - $end; 
    endif; 
} while ($start != $find); 

if ($start == $find): // ALWAYS true, can be omitted 
    echo "Found!"; 
endif; 
+0

謝謝你的回答。猜我需要編輯我的問題... – flux

0

費德里科幫助我理解錯誤,所以我會選擇他的答案。

而且,還這裏是我的回答,解釋了什麼是我想要實現:

<?php 

$start = 0; 
$end = 1; 
$find = 1; 

do { 
    $find = rand($start,$end); 
    echo $find."<br>"; 
} while ($start != $find); 

if ($start == $find): 
    echo "Found!"; 
endif; 

?> 

我刨使代碼工作,從_REQUEST所以取一個值,實際數量榮獲」 t是隨機的。我只是想了解什麼是錯誤的,以及如何使用rand();函數首次運行...