2011-04-03 150 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