我正在制作一个应用程序,它将为我提供用户插入的数字的均值,中值和范围。
但我似乎无法添加数字,然后将它们除以2
这就是我的尝试:
public static String Find_Mean()
{
int Number = 0;
for (int size = 0; size < list.Count; size++)
{
Number = Convert.ToInt16(list[size].ToString());
Number += Number;
}
int Final_Number = Number / 2;
return Convert.ToString(Final_Number);
}
我想要做的是将所有数字从arraylist中加起来然后除以2。
答案 0 :(得分:3)
尝试使用Linq:
int[] x;
x.Average();
x.Max();
x.Min();
答案 1 :(得分:3)
Number = Convert.ToInt32(list[size].ToString());
您在此处每次迭代都会覆盖数字的值。
答案 2 :(得分:1)
每次在循环中将Number
设置为数组列表元素并覆盖总数时,这就是为什么你没有得到总数。您需要使用单独的变量来维护总计。类似的东西:
int Number = 0;
int Total = 0;
for (int size = 0; size < list.Count; size++)
{
Number = Convert.ToInt16(list[size].ToString());
Total += Number;
}
int Final_Number = Total / 2;
如果您使用 .Net 2.0或更高版本,那么如果您可以使用generic列表List<int>
则会更好。
您还可以将循环中的转换更改为:
Number = Convert.ToInt32(list[0]);
由于Convert.ToInt32
也有对象类型的重载,如果您的数字类型为int
,则其为Int32
而不是Int16
。
答案 3 :(得分:1)
您将在此处为Number重新分配值:
for (int size = 0; size < list.Count; size++)
{
Number = Convert.ToInt16(list[size].ToString());
Number += Number;
}
试试这个:
for (int size = 0; size < list.Count; size++)
{
Number += Convert.ToInt16(list[size].ToString());
}
答案 4 :(得分:0)
以下是我目前用于计算一些简单统计数据的内容:
private void CalculateStatistics(IEnumerable<Double> valuesToAggregate)
{
// We need to iterate multiple times over the values, so it makes
// sense to create a list to improve performance.
var aggregateMe = valuesToAggregate.ToList();
if (aggregateMe.Count > 0)
{
// To calculate the median, the simplest approach
// is to sort the list.
aggregateMe.Sort();
// Cause we already sorted the list,
// the min value must be available within the first element.
Min = aggregateMe[0];
// the max value must be available within the last element.
Max = aggregateMe[aggregateMe.Count - 1];
// The average has really to be calculated, by another iteration run.
Mean = aggregateMe.Average();
// Taking the median from a sorted list is easy.
var midpoint = (aggregateMe.Count - 1) / 2;
Median = aggregateMe[midpoint];
// If the list contains a even number of element,
// the median is the average of the two elements around the midpoint.
if (aggregateMe.Count % 2 == 0)
Median = (Median + aggregateMe[midpoint + 1]) / 2;
}
else
{
// There is no value available to calculate some statistic.
Min = Double.NaN;
Max = Double.NaN;
Mean = Double.NaN;
Median = Double.NaN;
}
}
请注意,您可以改进此特定实现,具体取决于您获取的数据类型(字符串,双精度等)以及它们是如何存储的(它们是否已作为列表进入,您可以操作等等?)。
答案 5 :(得分:0)
public static String Find_Mean()
{
List<int> integerList = list.Select(q => int.Parse(q)).ToList();
var result = integerList.Sum() / 2;
return result.ToString();
}