我的任务是打印数组中一组数字的平均值和方差,并且我需要引用我已经完成的avg。但是我不明白我现在怎么能打印平均值。我正在运行程序时正在打印0。这是我的代码:
static double varianceValue(ref double avg, params double[] intValues)
{
double sum = 0;
double f = 0;
double number = 0;
double sv = 0;
double variance= 0;
foreach (int value in intValues)
{
sum += value;
}
for (int i = 0; i < intValues.Length; i++)
{
number = intValues[i];
avg = sum / intValues.Length;
f = number - avg;
sv += Math.Pow(f, 2);
}
variance = sv / (intValues.Length - 1);
return variance;
}
static void Main(string[] args)
{
double avg = 0;
Console.WriteLine("The avg of the variables in the array are: {0}", varianceValue(ref avg));
Console.WriteLine("\nThe variance of 11, 13, 17, 19, 23 is: {0}", varianceValue(ref avg, 11.0, 13.0, 17.0, 19.0, 23.0));
Console.ReadKey();
}
答案 0 :(得分:1)
此时您打印为零,因为调用
时数组为空 Console.WriteLine("The avg of the variables in the array are: {0}", varianceValue(ref avg));
首先调用方差函数w / array params(这也将设置avg)。然后单独调用avg。
static void Main(string[] args)
{
double avg = 0;
Console.WriteLine("\nThe variance of 11, 13, 17, 19, 23 is: {0}", varianceValue(ref avg, 11.0, 13.0, 17.0, 19.0, 23.0));
Console.WriteLine("The avg of the variables in the array are: {0}", avg);
Console.ReadKey();
}