gpt4 book ai didi

c# - 中位数 c# 错误计算

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:37 25 4
gpt4 key购买 nike

当我输入 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();

最佳答案

那是因为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

关于c# - 中位数 c# 错误计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36315430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com