这个php方法假设使用for循环将Fibonacci序列打印到指定值.我不确定为什么它不起作用?
<?php
function fib ($n) { // a function called fib, declaire variable n (the sequence number)
for ($n=0;$n<30;$n++) {
if ($n < 3) { return $n; } // if n is smaller than 3 return n (1 or 2)
else { return fib ($n - 1) + fib ($n - 2); }
/* if the number is 3 or above do 2 sums (n-1) and (n-2)
and then add the 2 sums together (n-1)+(n-2)
Example Fibonacci number 4
(4-1)+(4-2) = 5
3 + 2 = 5
*/
}
print $n;
?>
Run Code Online (Sandbox Code Playgroud)
Lee*_*vis 37
实际上有一种方法可以通过使用舍入来计算斐波纳契数而无需迭代:
http://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding
function getFib($n)
{
return round(pow((sqrt(5)+1)/2, $n) / sqrt(5));
}
Run Code Online (Sandbox Code Playgroud)
小智 7
斐波纳契的简单功能
function fibonacci($n,$first = 0,$second = 1)
{
$fib = [$first,$second];
for($i=1;$i<$n;$i++)
{
$fib[] = $fib[$i]+$fib[$i-1];
}
return $fib;
}
echo "<pre>";
print_r(fibonacci(50));
Run Code Online (Sandbox Code Playgroud)
小智 6
在这个例子中,我使用for循环并将长度限制为10:
$x = 0;
$y = 1;
for($i=0;$i<=10;$i++)
{
$z = $x + $y;
echo $z."<br />";
$x=$y;
$y=$z;
}
Run Code Online (Sandbox Code Playgroud)
输出:
1
2
3
5
8
13
21
34
55
89
144