在VB中开发Fibonacci系列

时间:2009-08-31 17:34:13

标签: vb.net

我正在尝试在VB中为Fibonacci系列编写代码,但我的系列中的一些值是不正确的。有人可以帮我处理代码吗?

以下是我到目前为止的情况。

Private Function FibNumber(number As Integer) As Integer

    If (number > 2) Then
        FibNumber = (FibNumber(number - 2) + FibNumber(number - 1))
    Else
        FibNumber = 1
    End If

    End Function

    Private Sub command1_click()
    Dim x As Integer
    x = Text1.Text
    Call FibNumber(number)

End Sub

5 个答案:

答案 0 :(得分:3)

好吧,我做了一个快速搜索,我在前几个结果中想出了以下内容:

Private Function FibNumber(number As Integer) As Integer

If (number > 2) Then
    FibNumber = (FibNumber(number - 2) + FibNumber(number - 1)) 
Else
    FibNumber = 1
End If

End Function

答案 1 :(得分:1)

我知道这已经过时了,但我认为问题可能在于compgeek如何调用该函数。

而不是:

Call FibNumber(number)

应该是:

Call FibNumber(x)

答案 2 :(得分:1)

我的解决方案:

Private Function FibNumber(number As Integer) As Integer
    If (number > 2) Then
       FibNumber = (FibNumber(number - 2) + FibNumber(number - 1))
    Else
       FibNumber = 1
    End If
End Function

Private Sub command1_click() 
    Dim x As Integer
    x = Text1.Text 
    Call FibNumber(number) 
End Sub 

答案 3 :(得分:0)

这是一个Java函数,相信我;斐波纳契不会比它快得多或复杂得多 这个特别的版本。它经过优化,运行速度比原始递归速度快100倍。

提示:您可能需要更改maxN以扩展参数长度! 例如,如果要输入0到199之间的数字,则必须将maxN增加到200

static final int maxN = 72;
static long knownF[] = new long[maxN];

static long F(int i) {
  if (knownF[i] != 0) {
    return knownF[i];
  }

  long t = i;

  if (i < 0) {
      return 0;
  }

  if (i > 1) {
      t = F(i - 1) + F(i - 2);
  }

  return knownF[i] = t;
}

答案 4 :(得分:0)

模块Module1

Sub Main()
    Console.WriteLine("The Fibonacci Series")
    Console.WriteLine("Enter how many elements-")
    Dim n As Integer = Console.ReadLine
    If (n = 1) Then
        Dim a As Integer = 1
        Console.WriteLine("{0}", a)
    Else
        Dim a As Integer = 1
        Dim b As Integer = 2
        Console.WriteLine("{0}", a)
        Console.WriteLine("{0}", b)
        Dim i As Integer = 1
        While (i < n - 1)
            Dim c As Integer = a + b
            Console.WriteLine(" {0}", c)
            a = b
            b = c
            i = i + 1
        End While
    End If
    Console.ReadKey()
End Sub

最终模块