【问题标题】:median c# wrong calculate中位数 c# 错误计算
【发布时间】:2016-03-30 17:11:37
【问题描述】:

当我输入 1,2、3 时,我的中位数计算有问题,我的中位数是 = 44,我不知道为什么

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();

【问题讨论】:

  • 您正在使用字符代码而不是数字进行计算 - 这就是原因。尝试使用 int.Parse() 解析它们

标签: c# winforms median


【解决方案1】:

那是因为44, 的ASCII 值。而在你的string中,现在使用你当前的方法,中位数是逗号字符, value = 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

【讨论】:

    【解决方案2】:

    您的问题是您使用字符而不是数字进行计算。
    所以假设你的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
    

    【讨论】:

      【解决方案3】:

      static void Main(string[] 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);
          }
      

      【讨论】:

      • 只是发布一个代码sn-p在这里不太受欢迎。您能否提供一些背景信息,如何为什么它解决了 OPs 问题?另请参考How to Answer
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2011-05-07
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多