从用户输入的数组中获取平均值

时间:2015-07-06 19:20:34

标签: c#

您好我正在尝试创建一个程序,要求用户输入最多25个数字,然后显示它们的平均值,但是当它询问数字时,它只是一直在询问数字而不是重复并且不显示平均值。

任何指导都将不胜感激。

static void Main(string[] args)
    {

        Console.WriteLine("enter the amount of numbers you would like to find the average and mean of: ");
        int arraylength = Int32.Parse(Console.ReadLine());
        int[] AverageArray = new int[25];


        //filling the array with user input
        for (int i = 0; i < AverageArray.Length; i++)
        {
            Console.Write("enter the numbers you wish to find the average for: ");
            AverageArray[i] = Int32.Parse(Console.ReadLine());

        }
        //printing out the array 
        Console.WriteLine("here is your array: ");
        for (int i = 0; i < AverageArray.Length; i++)
        {
            Console.WriteLine(AverageArray[i]);
        }
        Console.WriteLine(FindAverage(AverageArray));
    }


    public static double FindAverage(int[] averageNumbers)
    {
        int arraySum = 0;

        for (int i = 0; i < averageNumbers.Length; i++)
            arraySum += averageNumbers[i];

        return arraySum / averageNumbers.Length;
    }

}

1 个答案:

答案 0 :(得分:1)

您已经拥有arrayLength,为什么不将它用作数组大小指示器?此外,您的平均例程将失去精确度。您将返回double,但您的代码的所有内容都为int

static void Main(string[] args)
{
    Console.WriteLine("enter the amount of numbers you would like to find the average and mean of: ");
    int arraylength = Int32.Parse(Console.ReadLine());
    int[] AverageArray = new int[arraylength];

    //filling the array with user input
    for (int i = 0; i < arraylength; i++)
    {
        Console.Write("enter the numbers you wish to find the average for: ");
        AverageArray[i] = Int32.Parse(Console.ReadLine());
    }
    //printing out the array 
    Console.WriteLine("here is your array: ");
    for (int i = 0; i < arrayLength; i++)
    {
        Console.WriteLine(AverageArray[i]);
    }
    Console.WriteLine(FindAverage(AverageArray));
}

public static double FindAverage(int[] averageNumbers)
{
    // change to 'double' otherwise you will lose precision
    double arraySum = 0;
    for (int i = 0; i < averageNumbers.Length; i++)
        arraySum += averageNumbers[i];

    return arraySum / averageNumbers.Length;
}