2011-04-03 146 views
6

請你幫我顯示前10個斐波納契數。我的代碼顯示以下結果:1,2,3,5,8,13,21,34,55,我需要它也顯示前兩個斐波納契數(0和1)。我會怎麼做?VB.net中使用循環的斐波那契數列

Public Class Form1 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Dim a As Integer = 0 
    Dim b As Integer = 1 
    Dim fib As Integer = 0 

    Do 
     fib = a + b 
     a = b 
     b = fib 
     Label1.Text = Label1.Text + fib.ToString & ControlChars.NewLine 
    Loop While fib < 55 
    End Sub 
End Class 

凡在職業規劃,你會需要使用斐波那契序列?

回答

3

Do ... while前只需添加

Label1.Text = Label1.Text + a.ToString & ControlChars.NewLine 
Label1.Text = Label1.Text + b.ToString & ControlChars.NewLine 

對於鏈接到斐波那契數應用見:Fibonacci: Applications

2

代替計算在序列號的下一個,然後將結果相加,以輸出的,這樣做的以相反順序:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Dim a As Integer = 0 
    Dim b As Integer = 1 
    Dim fib As Integer 

    Do 
     Label1.Text += a.ToString & ControlChars.NewLine 
     fib = a + b 
     a = b 
     b = fib 
    Loop While a <= 55 

End Sub 
+0

這樣您不打印第一個值(0)也不打印最後一個值。 – log0 2011-04-04 21:59:04

+0

確實,謝謝你指出。糾正。 – Anax 2011-04-05 00:38:54

1

在同一你已經將你的代碼中的前兩個斐波那契數字定義爲0和1的方式,你應該在開始時將它們放入標籤字符串中(即不在循環中)。你也應該對你所計算的斐波納契數的數量使用一個循環條件,而不是依賴於知道第10個數是什麼。

我從來沒有在工作中使用斐波那契數字,但他們是一個很好的學習練習與天真的遞歸soloution,一個查找表,一個簡單的迭代soloution(如yours),使用黃金比例,矩陣形式...

-1
Dim a, b, c as integer 

a=0 

b=1 

print a 

print b 

while c<(n-c) 

c=a+b 

print c 

a=b 

b=c 

wend 

print "This is Fibonacci Series" 

End Sub 
0
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click 
    Dim a As Integer = 0 
    Dim b As Integer = 1 
    Dim fib As Integer 
    Dim userinput, i As Integer 
    userinput = InputBox("how many") 
    i = userinput 
    ListView3.Items.Add(1) 
    Do 
     fib = a + b 
     a = b 
     b = fib 
     ListView3.Items.Add(fib) 
     i = i + 1 
    Loop While fib < i 
End Sub 

末級

0

試試這個代碼:

Dim arr As New ArrayList() 
    Console.Write("The Fibonacci Series is : ") 
    For i As Integer = 0 To 10 
     If i = 0 Or i = 1 Then 
      arr.Add(i) 
      Console.Write(arr(i).ToString() + ", ")    
     Else 
      arr.Add(arr(i - 2) + arr(i - 1)) 
      If i = 10 Then 
       Console.Write(arr(i).ToString()) 
      Else 
       Console.Write(arr(i).ToString() + ", ") 
      End If 
     End If 
    Next 
    Console.Read() 
0

Pretty Symple,只需使用一個按鈕,您可以根據需要生成任意數量的序列。

Sub fibonacci() 

mycount = Application.CountA(Range("A:A")) 

e = mycount - 1 
fib = 0 
fib = Cells(e, 1).Value + Cells(e + 1, 1).Value 
Cells(mycount + 1, 1).Value = fib 
mycount = mycount + 1 

End Sub