简体   繁体   English

通过循环检查数字是否为斐波那契数

[英]Checking if a number is a Fibonacci number through a loop

so the task I'm trying to complete here is comparing a user input number against the fibonacci sequence and if it is a fibonacci number the program will echo true, if not it will echo false. 因此,我要在此处完成的任务是将用户输入数字与斐波那契数列进行比较,如果它是斐波那契数,则程序将回显true,否则将回显false。

Can someone tell me where I'm going wrong? 有人可以告诉我我要去哪里了吗?

this is my first file: 这是我的第一个文件:

<?php
function print_fibonacci($n){

    $first = 0;
    $second = 1;

    echo "Fibonacci Series: \n";

    echo $first.' '.$second.' ';

    for($i=2;$i<$n;$i++){

        $third = $first + $second;

        echo $third.' ';

        $first = $second;
        $second = $third;

    }
}


/* Function call to print Fibonacci series upto 6 numbers. */

print_fibonacci(16);

 ?>

<form method="POST" action="fibonacci3.php"><br>
<label>Input a number to check if it is fibonacci or not.</label><br>
<input name="fib" type="text" placeholder="#" /><br>
<input type="submit" value="OK!" />
</form>

This outputs the fibonacci sequence until the 16th fibonacci number, and is followed by a form which allows a user to enter a number. 这会输出斐波那契数列,直到第16个斐波那契数为止,然后是允许用户输入数字的表格。

The next file is fibonacci3.php as referenced in the form. 下一个文件是表单中引用的fibonacci3.php。

<?php

include "fibonacci2.php";

$n = $_POST["fib"];

function fibonacci($n) {

    //0, 1, 1, 2, 3, 5, 8, 13, 21

    /*this is an error condition
    returning -1 is arbitrary - we could
    return anything we want for this
    error condition:
    */
    if((int)$n <0){
        return -1;
        echo "False";
    }

    if ((int)$n == 0){
        return 0;
        echo "0";
    }

    if((int)$n == 1 || $n == 2){
        return 1;
    }

    $int1 = 1;
    $int2 = 1;

    $fib = 0;


    for($i=1; $i<=$n-2; $i++ )
    {
        $fib = $int1 + $int2;
        //swap the values out:
        $int2 = $int1;
        $int1 = $fib;
    }

    if ($fib = $int1 + $int2 && $n == $fib){
        echo "True!";
    } else {
        echo "False!";
    }

    return $fib;

}

fibonacci((int)$n);
?>

I thought this might be correct but it's not outputting anything when the user inputs a number. 我认为这可能是正确的,但是当用户输入数字时它不会输出任何内容。

$n = 'Your number';
$dRes1 = sqrt((5*pow($n, 2))-4);
    $nRes1 = (int)$dRes1;
    $dDecPoint1 = $dRes1 - $nRes1;
    $dRes2 = sqrt((5*pow($n, 2))+4);
    $nRes2 = (int)$dRes2;
    $dDecPoint2 = $dRes2 - $nRes2;
    if( !$dDecPoint1 || !$dDecPoint2 )
    {
        echo 'True';
    }
    else {
        echo 'False';
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM