我需要从一组数字中得出所有平均值(众数,均值,中位数,范围)。
计算器正在从NumericUpDown
获取输入并将其添加到listBox
,
将listBox项添加到List<Decimal>
中(因为打印到标签似乎更容易)。
对于每种平均方法,列表都将转换为Array
,因为它似乎更易于计算。
不说谎,我什至不知道从中位数开始...
我已经从StackOverflow上的各种解决方案中复制了一些代码,但没有用,但是它们都不起作用,因为它们不是为小数写的,而且说实话,我不太了解代码。
添加号码
//Add number to list and retun to 0.
private void btnAddNums_Click(object sender, EventArgs e)
{
//Add selcted item from listbox
listBoxNumbers.Items.Add(numUpDownAvg.Value);
//Create new instance of listNumbers
List<Decimal> listNumbers = new List<Decimal>();
//for each decimal in listbox...
foreach (Decimal listItems in listBoxNumbers.Items)
{
//Add to listNumbers
listNumbers.Add(listItems);
numUpDownAvg.Value = 0;
}
//iterate though list printing each item seperate by a comma
for (int i = 0; i < listNumbers.Count; i++)
{
txtBoxNumbers.Text = (String.Join(",", listNumbers));
}
//print list to console
Console.WriteLine(String.Join(",", listNumbers));
}
中位数
//This button prints median to results
private void btnMedian_Click(object sender, EventArgs e)
{
//Create new instance of listNumbers
List<Decimal> listNumbers = new List<Decimal>();
//for each decimal in listbox...
foreach (Decimal listItems in listBoxNumbers.Items)
{
//Add to listNumbers
listNumbers.Add(listItems);
}
//Convert list to array
decimal[] listArrayofNumbers = listNumbers.ToArray();
Array.Sort(listArrayofNumbers);
var n = listArrayofNumbers.Length;
decimal median;
var isOdd = n % 2 != 0;
if (isOdd)
{
median = listArrayofNumbers[(n + 1) / 2 - 1];
}
else
{
median = Convert.ToDecimal(listArrayofNumbers[n / 2 - 1] + listArrayofNumbers[n / 2]) / 2.0d;
}
// Console.WriteLine(median);
}
}
错误是median = Convert.ToDecimal(listArrayofNumbers[n / 2 - 1] + listArrayofNumbers[n / 2]) / 2.0d;
错误提示“运算符” /”不能与十进制或双精度类型的
一起使用假设我需要在某个地方转换为小数?显然Convert.ToDecimal是不正确的...
TIA!