2

当用户提交他/她的号码时,我的代码的 php 部分没有做正确的操作,例如,如果用户提交 5,我希望 rand 函数随机输出 5 作为所选数字;但是,我的代码有时有效,有时无效。

<!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>
4

3 回答 3

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.";
}
于 2009-10-10T01:43:18.583 回答
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";
}

另外,您不需要提交按钮吗?

于 2009-10-10T01:56:54.103 回答
1

认为您在这里尝试做的是要求用户输入骰子有多少面,然后输出值是多少?这个问题没有多大意义......但如果以上是你想要做的,这应该工作:

选择die.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"]);
}
?>

这将允许用户输入骰子的面数,然后打印出滚动的面数和面数。

于 2009-10-10T05:31:42.273 回答