2009-10-10 35 views
2

當用戶提交他/她的號碼時,我的代碼的php部分沒有執行正確的操作 ,例如,如果用戶提交5,我希望rand函數隨機輸出5作爲所選號碼;但是,我的代碼有時可以工作,而在其他時間不起作用。PHP選擇模具有的一面?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 


<head> 
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> 
<title> 
choose a die number 
</title> 
</head> 
<center> 
<body> 
<h1>Choose a die number</h1> 
<form method = "post" action="choosedie.php"/> 
<!--If the user selects a number of sides the die is suppose to have 
rand should go through and pick the number randomly, and echo out the 
number that was entered by the user--> 

Please choose how many sides a die should have from 1 through 6: 
<br/> 
<input type = "text" name = "roll"/> 
<?php 


//Roll a random dice from 1 through 6: 
$roll = rand(1,6); 
// Add random variable to do comparison on. 

有沒有辦法讓我在這裏比較rand而不必創建另一個變量?

$random = rand(1,6); 

// If $roll is equal to $random echo the output out to the user. 
If ($roll == $random) 
{ 
echo "<br/>Here is the random $roll with the appropriate maximum value $random\n"; 

如果用戶選擇5,我希望這個回顯5,但我得到不同的值?

} 


?> 


</body> 
</center> 
</html> 

回答

1

認爲你在這裏要做的是要求用戶輸入模具有多少面,然後輸出什麼值?這個問題不會使一個很大的意義...但如果上面是你想要做什麼,這應該工作:

choosedie.php

<h1>Choose a die number</h1> 
<form method = "post" action="choosedie.php"/> 
Please choose how many sides a die should have from 1 through 6: 
<br/> 
<input type="text" name="roll"/> 
<input type="submit" value="Submit" /> 
</form> 

<?php 
if (isset($_POST["roll"])) { 
    $roll = rand(1, $_POST["roll"]); 
    printf("A %s was rolled, with a maximum roll of %s", $roll, $_POST["roll"]); 
} 
?> 

這將使用戶輸入一個模具的邊數,然後打印出與邊數一起滾動的數據。

+0

即使這個問題沒有什麼意義,但你可以從用戶那裏得到我想要的東西,這很棒。 謝謝。 – Newb 2009-10-11 20:05:40

6

由於rand(n,m)返回一個整數值,你應該能夠做的正是如此:

if(rand(1,6) == $guess){ 
    echo "Congratulations - your guess of $guess was right!"; 
} 
else{ 
    echo "No dice - better luck next time."; 
} 
+1

謝謝,這真的說明了如何操作和使用rand和if和else構造來做比較。 – Newb 2009-10-10 04:31:55

+0

開心就是你在找的東西:) – warren 2009-10-10 05:28:54

1

我不知道你想做什麼。每次加載該頁面時,它都會選取兩個隨機數,即$ random和$ roll,如果相等,則打印它們。

如果你想獲得用戶輸入,你需要使用$ _POST。

$users_dice_roll = $_POST["roll"]; 
$random_dice_roll = rand(1,6); 
if($random_dice_roll == $users_dice_roll){ 
    echo "You rolled: $users_guess"; 
} 

此外,您是否需要提交按鈕?