如何在数组中存储随机数并输出它们的平均值?

时间:2015-11-16 16:59:51

标签: c# arrays random numbers int

我正在尝试制作一个输出30个随机数的程序并将它们存储在一个数组中,然后需要找到这30个数字的平均值并将其输出给我。到目前为止,我有这样的结果:(对不起,如果我对此不好,我对编程很陌生)感谢任何反馈:)

    {
        Random r = new Random();

        int sum = 0;
        int count = 30;

        int[] numbers = new int[30] { r.Next(1, 100) };
        for (int i = 0; i < 30; i++)

        Console.WriteLine(r.Next(1, 100).ToString());
        Console.ReadLine();

        int y = r.Next();
        int avg = (int)sum / count;

        Console.WriteLine("The average is: {0}", avg);
        Console.ReadLine();


    }

2 个答案:

答案 0 :(得分:2)

代码中存在一些问题。你可以这样做:

Random r = new Random();

int count = 30;

// Create an array with count elements.
int[] numbers = new int[count];

// Loop over each index
for (int i = 0; i < count; i++)
{
    // Generate and store a random number at current index
    numbers[i] = r.Next(1, 100);
}

// Calculate the average
double avg = numbers.Average();

// Print the average
Console.WriteLine("The average is: {0}", avg);
Console.ReadLine();

答案 1 :(得分:1)

您不需要阵列,只需在找到下一个号码后添加总和即可。

        Random r = new Random();
        int sum = 0;
        int count = 30;

        for (int i = 0; i < count; i++)
        {
            // Find your next random number
            var newNum = r.Next(1, 100);

            // Display it
            Console.WriteLine(newNum.ToString());

            // Add it to your running total
            sum += newNum;
        };

        Console.ReadLine();
        int avg = (int)sum / count;

        Console.WriteLine("The average is: {0}", avg);
        Console.ReadLine();