2014-02-09 28 views
1

我正在嘗試編寫一個C#函數來確定數組中的最大值並通過引用傳遞它。在靜態void函數中傳遞參數C#

這是在C#中我第一次編程,但它的真正纏着我,我不來似乎能夠在主正確分配它。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication4 
{ 
    class Program 
    { 
     static void Maxim(int n, ref int maxim, params int[] v) { 
      int i, max=v[0]; 

      for (i = 0; i < n; i++) { 
       if (v[i] > max) max = v[i]; 
      } 
     } 

     static void Main() 
     { 
      int[] vector = new int[10]; 
      int n, i; 
      int maximul; 

      Console.WriteLine("Introduceti numarul de elemente: "); 
      n = Int32.Parse(Console.ReadLine()); 

      Console.WriteLine("Valoarea introdusa: {0}", n); 
      for (i = 0; i < n; i++) { 
       vector[i] = Int32.Parse(Console.ReadLine()); 
      } 

      Console.WriteLine("Elementele introduse sunt: "); 
      for (i = 0; i < n; i++) { 
       Console.WriteLine("Elementul {0}: {1}", i + 1, vector[i]); 
      } 

      Maxim(n, ref maximul, vector); 

      Console.WriteLine("Maximul din vector: {0}", maximul); 
      Console.ReadLine(); 
     } 
    } 
} 

它給我返回以下錯誤:Use of unassigned local variable

+1

嘗試設置maximul = 0;在宣言中。 –

+1

你從未在'Maxim'函數中分配'maxim'。 – MPelletier

+1

看到這個問題的最多的回答對'out'解釋VS'ref':http://stackoverflow.com/questions/135234/difference-between-ref-and-out-parameters-in-net – MPelletier

回答

3

當你定義它們初始化變量:

int n = 0, i = 0; 
int maximul = 0; 

大概的原因是你逝去的maximul裁判參數,但你沒有初始化。

documentation

An argument that is passed to a ref parameter must be initialized before it is passed. This differs from out parameters, whose arguments do not have to be explicitly initialized before they are passed.

+0

是的,現在我理解!非常感謝! –

+0

您不需要在代碼中使用ref。只要傳遞價值就好。並沒有使用maximul。 – 2014-02-09 01:27:39

0

馬克西姆是冗餘變量。你從來沒有在你的功能中使用它。

+0

謝謝!這是代碼中的錯誤之一!:) –

0

問題是最大值被存儲在本地max中,但調用者期待它被寫入ref參數maxim。如果您刪除本地max並使用maxim,則會解決此問題。

更習慣的方法來寫這個功能是不使用ref參數在所有。相反,只返回值直接

static intMaxim(int n, params int[] v) { 
    int i, max=v[0]; 
    for (i = 0; i < n; i++) { 
    if (v[i] > max) max = v[i]; 
    } 
    return max; 
} 

注意,n參數也沒有真正在這裏需要。陣列v的長度可以通過表達式來訪問v.Length

相關問題