动态传递函数中的参数数组

时间:2016-07-06 08:26:19

标签: vb.net

我的代码有些问题。你能帮我找一个关于这个程序的解决方案吗?

Module Module1
Function AddElements(ParamArray arr As Integer()) As Integer
    Dim sum As Integer = 0
    Dim i As Integer = 0
    For Each i In arr
        sum += i
    Next i
    Return sum
End Function
Sub Main()
    Dim sum As Integer
    Dim k As Integer()
    Dim j As Integer
    Dim n As Integer
    Console.WriteLine("Enter the Array Value")
    n = Console.ReadLine()
    For j = 1 To n
        Console.WriteLine("Enter the value of:")

        k(j) = Console.ReadLine()

    Next
    sum = AddElements(k(j))
    sum = Console.ReadLine()

    Console.WriteLine("The sum is: {0}", sum)


    Console.ReadLine()
End Sub

End Module

1 个答案:

答案 0 :(得分:0)

  1. 你需要用它应该具有的大小来初始化k()。
  2. 正如JRSofty所说,您当前正在向该函数传递单个int而不是数组。
  3. sum = Console.ReadLine()有什么意义?您计算总和,然后使用控制台的输入覆盖该值。
  4. 更正后的代码

    Module Module1
    Function AddElements(ParamArray arr As Integer()) As Integer
        Dim sum As Integer = 0
        Dim i As Integer = 0
        For Each i In arr
            sum += i
        Next i
        Return sum
    End Function
    Sub Main()
        Dim sum As Integer
        Dim j As Integer
        Dim n As Integer
        Console.WriteLine("Enter the Array Value")
        n = Console.ReadLine()
        Dim k(n) As Integer '1
        For j = 1 To n
            Console.WriteLine("Enter the value of:")           
            k(j) = Console.ReadLine()  
        Next
        sum = AddElements(k) '2
        'sum = Console.ReadLine() '3
    
        Console.WriteLine("The sum is: {0}", sum)
    
    
        Console.ReadLine()
    End Sub
    
    End Module