1

好吧,我试图完成一个挑战,要求我从 0 到 1000 获得所有 5 或 3 的倍数,然后得到它们的总和,我是 vb.net 的新手,所以我认为这将是一个不错的选择我要解决的挑战> 我很确定我的基础知识是正确的,但我不太确定为什么会出现这个错误:/。

Module Module1

    Sub Main()
        Dim Counter As Integer = 1
        Dim Numbers() As Integer
        Dim NumbersCounter As Integer = 0
        Dim Total As Integer = 0

        While (Counter <= 1000)

            If (Counter Mod 3 = 0) Then
                Numbers(NumbersCounter) = Counter '<--- The error is located on Numbers.
                NumbersCounter = NumbersCounter + 1
                Counter = Counter + 1

            ElseIf (Counter Mod 5 = 0) Then
                Numbers(NumbersCounter) = Counter
                NumbersCounter = NumbersCounter + 1
                Counter = Counter + 1

            Else
                Counter = Counter + 1
            End If

        End While

        Counter = 0

        While (Counter <= Numbers.Length)
            If (Counter = 0) Then
                Total = Numbers(Counter)
                Counter = Counter + 1
            Else
                Total = Total * Numbers(Counter)
                Counter = Counter + 1
            End If

        End While

        PrintLine(Total)

    End Sub

End Module

任何帮助或提示将不胜感激!提前致谢。

4

2 回答 2

1

您需要为 Numbers 数组分配内存,并且由于最初知道大小,您可以在声明时分配:

Dim Numbers(1000) As Integer

于 2012-07-21T00:19:02.093 回答
1

在查看您的代码时,蛋头说您没有初始化您的数组是正确的。但是在这样做之后,我必须更改代码中的其他一些内容才能使其运行。

Module Module1

    Sub Main()
        Dim Counter As Integer = 1
        Dim Numbers(1000) As Integer          'Initialized the Array so it will be usable.
        Dim NumbersCounter As Integer = 0
        Dim Total As Integer = 0

        While (Counter <= 1000)

            If (Counter Mod 3 = 0) Then
                Numbers(NumbersCounter) = Counter 
                NumbersCounter = NumbersCounter + 1
                Counter = Counter + 1

            ElseIf (Counter Mod 5 = 0) Then
                Numbers(NumbersCounter) = Counter
                NumbersCounter = NumbersCounter + 1
                Counter = Counter + 1

            Else
                Counter = Counter + 1
            End If

        End While

        Counter = 0

        While (Counter <= Numbers.Length - 1)  ' Arrays are zero based so you need to subtract 1 from the length or else you will overflow the bounds
            If (Counter = 0) Then
                Total = Numbers(Counter)
                Counter = Counter + 1
            Else
                Total = Total + Numbers(Counter)  'You were multiplying here not adding creating a HUGE number
                Counter = Counter + 1
            End If

        End While

        Console.WriteLine(Total)  'Changed PrintLine which prints to a file to Console.WriteLine which writes to the screen
        Console.ReadLine          'Added a Console.ReadLine so the Window doesn't close until you hit a key so you can see your answer

    End Sub

End Module
于 2012-07-21T05:18:26.663 回答