【问题标题】:C# fibonacci function returning errorsC#斐波那契函数返回错误
【发布时间】:2010-11-07 17:46:53
【问题描述】:

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

我所做的是:

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;
    }
}

谁能告诉我我在这里做错了什么?

【问题讨论】:

  • 您的意思是#DEFINE 错误吗?
  • 只是好奇,但你为什么返回一个 int 而不是 bool?
  • @Joel 我猜他是在 C# 之前被介绍给 C 的,其中 bool 不存在,整数值 10 通常用于 true 和 @987654326 @,分别。

标签: c# console-application fibonacci


【解决方案1】:

嗯,对于初学者来说,您的数组只有 10 长,并且您正在用大约 100 个项目(超出范围异常)填充它 - 但有更好的方法来做到这一点......

例如,使用this post:

long val = ...
bool isFib = Fibonacci().TakeWhile(x => x <= val).Last() == val;

【讨论】:

    【解决方案2】:

    您可以做的一件事是检查是否提前退出。由于您正在尝试确定给定数字是否在斐波那契数列中,因此您可以进行边界检查以提前退出。

    例子:

    static bool isFibonacci(int n)
    {
        int[] fib = new int[100];
        fib[0] = 1;
        fib[1] = 1;
        for (int i = 2; i <= fib.Length; i++)
        {
            fib[i] = fib[i - 1] + fib[i - 2];
    
            if (n == fib[i])
            {
                return true;
            }
            else if (n < fib[i])
            {
                return false;  //your number has been surpassed in the fib seq
            }
        }
        return false;
    }
    

    【讨论】:

    • 如果遇到数组末尾可能应该抛出异常:在这种情况下函数无法给出答案。
    【解决方案3】:
    int[] fib = new int[10];
    for (int i = 2; i <= *100*; i++)
    

    您将超出数组的范围,因为您的循环条件太大。更传统的方法是通过数组的大小来限制循环:

    for (int i = 2; i < fib.Length; i++)
    

    让你的数组更大,但正如 Marc 所说,有更好的方法可以做到这一点,我建议你花一些时间阅读维基百科上的 Fibonacci numbers 文章。

    【讨论】:

      【解决方案4】:

      这是一个使用无限迭代器块的有趣解决方案:

      IEnumerable<int> Fibonacci()
      {
         int n1 = 0;
         int n2 = 1;
      
         yield return 1;
         while (true)
         {
            int n = n1 + n2;
            n1 = n2;
            n2 = n;
            yield return n;
         }
      }
      
      bool isFibonacci(int n)
      {
          foreach (int f in Fibonacci())
          {
             if (f > n) return false;
             if (f == n) return true;
          }
      }
      

      我真的很喜欢这种斐波那契实现与传统的递归解决方案相比,因为它使用于完成一个术语的工作可用于完成下一个术语。传统的递归解决方案重复了一些工作,因为它每个术语需要两次递归调用。

      【讨论】:

        【解决方案5】:

        问题在于

        for (int i = 2; i <= 100; i++)
        

        更重要的是=。没有 fib[100] (C# 零计数),因此当您检查 i=100 时会出现异常。

        正确的说法应该是

        for (int i = 2; i < 100; i++)
        

        甚至更好

        for (int i = 2; i < fib.Length; i++)
        

        【讨论】:

        • +1 我很惊讶最高答案和接受的答案没有指出错误的原因。 这是他的代码的实际问题。由于访问fib[100],而最后一项是fib[99],他得到索引超出范围异常
        【解决方案6】:
        public static int FibNo(int n) {
            int result = 0; int No = 0; int N1 = 1;
        
            if (n< 0)
            { throw new ArguementException("number must be a positive value"); }
        
            if (n <= 1) 
            { result = n; return result; }
        
            for(int x=1; x < n; x++) 
            { result = No + N1; No = N1; N1=result; }
        
            return result;
        
        }
        

        【讨论】:

          【解决方案7】:

          这里有一个比你所有的解决方案都好!

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

          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;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-04-06
            • 1970-01-01
            • 1970-01-01
            • 2021-02-14
            • 2014-05-03
            • 2011-08-10
            • 1970-01-01
            • 2013-03-04
            相关资源
            最近更新 更多