假设此php方法使用for循环将斐波那契序列打印到指定值。我不确定为什么它不能工作?
<?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;
?>发布于 2014-11-28 21:57:59
实际上,有一种方法可以通过四舍五入来计算Fibonacci数,而无需迭代:
http://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding
function getFib($n)
{
return round(pow((sqrt(5)+1)/2, $n) / sqrt(5));
}发布于 2013-08-10 04:38:57
fibonacci的简单函数
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));发布于 2014-04-17 14:35:00
在本例中,我使用了for循环,并将长度限制为10:
$x = 0;
$y = 1;
for($i=0;$i<=10;$i++)
{
$z = $x + $y;
echo $z."<br />";
$x=$y;
$y=$z;
} 输出:
1
2
3.
5
8
13
21
34
55
89
144
https://stackoverflow.com/questions/15600041
复制相似问题