2013-10-11 52 views
0

誰能幫助我瞭解如何通過傳遞一個變量的循環?我想輸出變量$ guess,直到40 &打印出「你猜到低」或「你猜得太高」......如何將變量連接到計數器?比索傳遞變量通過一個for循環

$Me=30; 
$guess=$i; 

for ($i = 0; $i < 40; $i++) { 
    if($Me>$guess){ 
    print "$guess:you guessed too low<br />"; 
    }elseif($Me<$guess){ 
    print "$guess: you guessed to high<br />"; 
    }else{ 
    print "you guessed my age! i'm 31!"; 
    } 
} 

回答

1
$Me=30; 

for ($i = 0; $i < 40; $i++) { 
$guess=$i; // move it here 
    if($Me>$guess){ 
    print "$guess:you guessed too low<br />"; 
    }elseif($Me<$guess){ 
    print "$guess: you guessed to high<br />"; 
    }else{ 
    print "you guessed my age! i'm 31!"; 
    } 
} 
+0

謝謝llya! – Vynce82

1

在for循環使用$猜測$代替我。

但是,該程序將打印 「我31」 雖然我的$ = 30。

+0

謝謝!你的方式也行得通! – Vynce82

1
$Me=30; 
/* actually you don't need to use $guess=$i; for your needs */ 
for($i = 0; $i < 40; $i++) { 
    if($i < $Me){ 
     echo "$i:you guessed too low <br/>"; 
    } 
    else if($i > $Me){ 
     echo "$i: you guessed to high<br/>"; 
    } 
    else{ 
     echo "you guessed my age! i'm 31!"; 
    } 
} 
1
$Me=30; 

for ($i = 0; $i < 40;) { 
    $guess=$i; 
    if($Me>$guess){ 
     print "$guess:you guessed too low<br />"; 
    }elseif($Me<$guess){ 
     print "$guess: you guessed to high<br />"; 
    }else{ 
     print "you guessed my age! i'm 31!"; 
    } 
$i++; 
}