2016-07-06 63 views
-2

我有這個代碼的一些問題。你能幫我找到關於這個計劃的解決方案嗎?在函數中動態傳遞參數數組

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 
+0

它看起來像你只通過一個單一的元素,而不是整個數組的AddElements功能。 – JRSofty

回答

0
  1. 你需要用它應該有大小來初始化K()。
  2. 由於JRSofty表示您當前正在將一個int而不是一個數組傳遞給該函數。
  3. sum = Console.ReadLine()是什麼意思?您計算總和,然後用控制檯的輸入覆蓋該值。

更正代碼

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