如何使斐波那契停止在 php 中的最后一个输入数字

how to make fibonacci stop by last input number in php

我有这样的输入和输出:

输入:3
输出:1 1 2 3

输入:5
输出:1 1 2 3 5

输入:12
输出:1 1 2 3 5 8

输入:25
输出:1 1 2 3 5 8 13 21

我试过用这段代码总结一下:

<?php
  function fibonaci($total)
        {
            $previousNum=1;
            $numbersNow=1;

            $valueOutput = "$previousNum $numbersNow";

            for ($i=1; $i<$total; $i++)
            {
              $output = $numbersNow + $previousNum;
              $valueOutput = $valueOutput . " $output";

              $previousNum = $numbersNow;
              $numbersNow = $output;
            }
            return $valueOutput;
        }

        echo fibonaci(3);
        echo "<br>";

        echo fibonaci(5);
        echo "<br>";

        echo fibonaci(12);
        echo "<br>";

        echo fibonaci(25);
        echo "<br>";
?>

输出:
1 1 2 3
1 1 2 3 5 8
1 1 2 3 5 8 13 21 34 55 89 144 233
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393

我会将您的代码重写为:

function fibonaci($total)
{
    $previousNum=1;
    $numbersNow=1;

    $valueOutput = "$previousNum $numbersNow";

    while (true)
    {
      $output = $numbersNow + $previousNum;

      // break the loop if next number is greater than $total
      if ($output > $total) {
          break;
      }

      $valueOutput = $valueOutput . " $output";

      $previousNum = $numbersNow;
      $numbersNow = $output;
    }
    return $valueOutput;
}

Fiddle here.