C#fibonacci函数返回错误 [英] C# fibonacci function returning errors

查看:61
本文介绍了C#fibonacci函数返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在练习C#控制台应用程序,并且试图获取该函数以验证数字是否出现在斐波那契数列中,但我遇到了错误。

I am practising a C# console application, and I am trying to get the function to verify if the number appears in a fibonacci series or not but I'm getting errors.

我所做的是:

class Program
{
    static void Main(string[] args)
    {
        System.Console.WriteLine(isFibonacci(20));
    }
    static int isFibonacci(int n)
    {
        int[] fib = new int[100];
        fib[0] = 1;
        fib[1] = 1;
        for (int i = 2; i <= 100; i++)
        {
            fib[i] = fib[i - 1] + fib[i - 2];

            if (n == fib[i])
            {
                return 1;
            }



        }
        return 0;
    }
}

有人可以告诉我我在做什么错吗?

Can anybody tell me what am I doing wrong here?

推荐答案

这是一个击败您所有人的解决方案!

And here is a solution that beats all of yours!

为什么,当您有聪明的数学家为您做闭式解决方案时,为什么迭代? :)

Because, why iteration when you have smart mathematicians doing closed-form solutions for you? :)

static bool IsFibonacci(int number)
{
    //Uses a closed form solution for the fibonacci number calculation.
    //http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression

    double fi = (1 + Math.Sqrt(5)) / 2.0; //Golden ratio
    int n = (int) Math.Floor(Math.Log(number * Math.Sqrt(5) + 0.5, fi)); //Find's the index (n) of the given number in the fibonacci sequence

    int actualFibonacciNumber = (int)Math.Floor(Math.Pow(fi, n) / Math.Sqrt(5) + 0.5); //Finds the actual number corresponding to given index (n)

    return actualFibonacciNumber == number;
}

这篇关于C#fibonacci函数返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆