我正在玩一个非常简单的程序,采取一系列的双打,并返回标准偏差.这部分工作,但我想使代码更可重用.我想这样做,所以该方法可以接受任何可以被认为是数字的类型的参数,并返回标准偏差,而不是硬编码双重类型(像我最初在这个程序中).一个人如何去做,这是什么适当的术语?
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication5 { class Program { static void Main(string[] args) { double[] avg = { 3.4,55.6,10.0,4.5,2,2 }; double x = avg.Average(); //first round of testing Console.WriteLine("The average of the first array is below "); Console.WriteLine(x); Console.WriteLine("below should be the standard deviation!"); Console.WriteLine(CalculateStandardDeviation(avg)); Console.ReadLine(); int[] intAvg = { 4,3,5,6,2 }; double secondAvg = intAvg.Average(); Console.WriteLine("The average of the second array is below "); Console.WriteLine(secondAvg); //this is where the error is happening //CalculateStandardDeviation(secondAvg); } //this is where I tried to make the query more reusable public static double CalculateStandardDeviation(IEnumerable<double> values) { double avg = values.Average(); double sum = 0; foreach (double d in values) { sum += Math.Pow((d - avg),2); } return Math.Pow(sum / (values.Count() - 1),.5); } } }
解决方法
你可以使用这样的东西:
public static decimal CalculateStandardDeviation<T>(IEnumerable<T> values) { IEnumerable<decimal> decimalValues = values.Select(v => Convert.ToDecimal(v)); decimal result = 0; // calculate standard deviation on decimalValues return result; }
如果值包含不能转换为小数的值,它将抛出一个异常,但是如果值是适当的类型,那么它将会起作用,我认为这是完全正确的.