2016-03-30 39 views
1

我有問題,中位數計算,當我把1,2,3我位數= 44我不知道爲什麼中位數C#錯誤計算

double wynik = 0; 
string x1 = textBox1.Text; 
string[] tab = x1.Split(','); 
int n = tab.Length; 

Array.Sort(tab); 

if (n % 2 == 0) 
{ 
    double c = x1[(n/2) -1]; 
    double v = x1[(n/2)]; 
    wynik = (c + v)/2; 
} 
else 
    wynik = x1[n/2]; 

     textBox2.Text = wynik.ToString(); 
+4

你正在計算你唱字符代碼,而不是數字 - 這就是爲什麼。嘗試使用'int.Parse()'解析它們' –

回答

1

您的問題是,您正在計算字符,而不是數字。
因此,假設您的textBox1.Text"1,2,3"。然後x1[(n/2)-1]將指向字符'1',它的double值爲48或其他東西。

你需要使用int.Parse解析字符串轉換成int:

int[] tab = x1.Split(',').Select(s => int.Parse(s)).ToArray(); 

然後使用這些值,而不是再次的字符串:

if (n % 2 == 0) 
{ 
    double c = tab[(n/2) -1]; // tab instead of x1! 
    double v = tab[(n/2)]; // tab instead of x1! 
    wynik = (c + v)/2; 
} 
else 
    wynik = tab[n/2]; // tab instead of x1 
7

這是因爲44是ASCII值的,。而在你string,現在使用當前的方法,中間是逗號字符,值= 44

要獲得中位數,由,分割字符串的考慮,然後每個值轉換爲數字數據(如int ),然後對其進行排序,並簡單地得到排序後的數據中的中間值。

double wynik = 0; 
string x1 = textBox1.Text; 
int[] tab = x1.Split(',').Select(x => Convert.ToInt32(x)).ToArray(); //this is the trick 
int n = tab.Length;  
Array.Sort(tab); 
int median = tab[n/2]; //here is your median 
0

靜態無效的主要(字串[] args) {

 Console.WriteLine("Define Array Size"); 
     int size = Convert.ToInt32(Console.ReadLine()); 
     float reference = 0; 
     int[] newArray = new int[size]; 
     for (int i = 0; i < newArray.Length; i++) 
     { 
      newArray[i] = Convert.ToInt32(Console.ReadLine()); 
      reference = reference + newArray[i]; 
     } 
     float Median = reference/newArray.Length; 
     Console.WriteLine("The Median is ="+Median); 
    } 
+1

只是發佈代碼片段在這裏不是很感激。你能否給出一些背景知識,*如何*和*爲什麼*它解決了OP問題?請參考[答案]。 –