我在使用输入代码处理等式时遇到了一些问题。我已经尝试了一段时间(我是新编码)和搜索,但却无法以任何方式使其工作。这就是我最终的结果。谁能帮我?提前谢谢。
<!DOCTYPE HTML>
<html>
<body>
<form action="" method="post">
<br />Choose a number to be the nth in the Fibonacci sequence: <input type="number" name="fibnum">
<input type="submit">
</form> <br /> <br />
<?php
if(isset($_POST['fibnum'])){
$fibnum = $_POST['fibnum'];
function fibRec($fibnum){
if ($fibnum < 0){
echo "There are no Fibonacci numbers of negative values.";
}
elseif ($fibnum == 0){
echo "0";
}
elseif ($fibnum == 1){
echo "1";
}
else {
$sum = fibRec($fibnum-1)+fibRec($fibnum-2);
echo $sum;
}
}
$fib = fibRec($fibnum);
echo $fib;
}
?>
</body>
</html>
答案 0 :(得分:2)
使其工作只需要将回声改为如下所示的回报:
<?php
$_POST['fibnum']=11;
if(isset($_POST['fibnum'])){
$fibnum = $_POST['fibnum'];
function fibRec($fibnum){
if ($fibnum < 0){
return ( "There are no Fibonacci numbers of negative values.");
}
elseif ($fibnum == 0){
return ("0");
}
elseif ($fibnum == 1){
return ("1");
}
else {
$sum = fibRec($fibnum-1)+fibRec($fibnum-2);
return ($sum);
}
}
$fib = fibRec($fibnum);
echo $fib;
}
?>
答案 1 :(得分:0)
你正在把整数推向回声。在递归公式中,返回值将返回到调用实体,而不是在函数外部自动返回。
看看这个:
<!DOCTYPE HTML>
<html>
<body>
<form action="" method="post">
<br />Choose a number to be the nth in the Fibonacci sequence: <input type="number" name="fibnum">
<input type="submit">
</form> <br /> <br />
<?php
if(isset($_POST['fibnum'])){
$fibnum = $_POST['fibnum'];
function fibRec($fibnum){
if ($fibnum < 0){
echo "There are no Fibonacci numbers of negative values.";
}
elseif ($fibnum == 0){
return 0;
}
elseif ($fibnum == 1){
return 1;
}
else {
$sum = fibRec($fibnum-1)+fibRec($fibnum-2);
return $sum;
}
}
$fib = fibRec($fibnum);
echo $fib;
}
?>
</body>
</html>
答案 2 :(得分:0)
您还可以使用与黄金比率相关的PHI
常数来计算第n个斐波那契数。认为直到第5次迭代的斐波那契数都不是黄金比率,所以您可以像下面这样:
<?php
$fibnum = intval($_POST['fibnum']);
const PHI = 1.6180339887;
$f = [0, 1, 1, 2, 3];
echo getNthFibo($fibnum);
function getNthFibo($i)
{
if($i < 5){
return $f[$i];
}
// Starting from 5th iteration of fibo function
$n = 5;
$fn = 3;
while ($n < $i) {
$fn = round($fn * PHI);
$n++;
}
return $fn;
}