现在,我正在一个PHP项目中,用户输入下限和上限,程序将在该限制之间生成5个数字,将其打印出随机生成的5个数字,然后查找并打印总和。
由于某种原因,我的程序无法通过输入(上下限)。
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Sum of the Digits!</title>
</head>
<body>
<h1>Find the sum of five digits!</h1>
<p>Enter in the lower and upper limits of the numbers you would like to
generate. Press "Calculate" to calculate the sum of the genreated numbers!
</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter the lower limit: <input type = "number" name = "lowLim">
Enter the upper limit: <input type = "number" name = "upLim">
<input type = "submit">
</form>
<?php
if($SERVER["REQUEST_METHOD"] == "POST"){
$lowerLim = test_input($_POST["lowLim"]);
$upperLim = test_input($_POST["upLim"]);
$randomArray = array();
$sumArray = array();
$total = 0;
$arrCounter = 0;
var_dump ($lowerLim);
for($i = 0; $i < 5; $i++){
$randomRange = rand("$lowerLim","$upperLim");
$randomArray = array($randomRange[i]);
}
$sumArray = array($randomArray);
$total = array_sum($sumArray);
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
echo "First number generated: ".$randomArray[0];
echo "Second number generated: ".$randomArray[1];
echo "Third number generated: ".$randomArray[2];
echo "Fourth number generated: ".$randomArray[3];
echo "Fifth number generated: ".$randomArray[4];
echo "The sum of the generated digits is:".$total;
?>
</body>
</html>
答案 0 :(得分:0)
您的代码中有几个问题:
$_SERVER
,而不是$SERVER
if ... == POST
括号内,否则它们将与输入一起调用在分配随机值的循环中,您不断覆盖$ randomArray
array_sum()
需要直接在$randomArray
上调用,而不是在
随机数组的数组。
这是您的代码的更正版本:
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Sum of the Digits!</title>
</head>
<body>
<h1>Find the sum of five digits!</h1>
<p>Enter in the lower and upper limits of the numbers you would like to
generate. Press "Calculate" to calculate the sum of the genreated numbers!
</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter the lower limit: <input type = "number" name = "lowLim">
Enter the upper limit: <input type = "number" name = "upLim">
<input type = "submit">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$lowerLim = test_input($_POST["lowLim"]);
$upperLim = test_input($_POST["upLim"]);
$randomArray = array();
$sumArray = array();
$total = 0;
$arrCounter = 0;
var_dump ($lowerLim);
for($i = 0; $i < 5; $i++)
{
$randomRange = rand("$lowerLim","$upperLim");
$randomArray[] = $randomRange;
}
$total = array_sum($randomArray);
echo "First number generated: " . $randomArray[0];
echo "Second number generated: " . $randomArray[1];
echo "Third number generated: " . $randomArray[2];
echo "Fourth number generated: " . $randomArray[3];
echo "Fifth number generated: " . $randomArray[4];
echo "The sum of the generated digits is:".$total;
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>