C #: генерировать 100 случайных чисел от 1 до 1000 и выводить максимальное значение - PullRequest
0 голосов
/ 23 февраля 2019

Я очень плохо знаком с кодированием и просто не могу обернуться вокруг Loops / Arrays / Randoms.Я понимаю концепцию, но когда дело доходит до ее применения, я просто теряюсь.

Здесь я пытаюсь сгенерировать 100 случайных чисел в диапазоне от 1 до 1000, и оно должно вывести максимальное значение.Вот мой код:

Random rnd = new Random();
int nums = rnd.Next(0, 1001);
for (int i = 1; i <= 100; i++)
{

}
Console.WriteLine(nums);
Console.ReadLine(); 

Это дает мне только один номер.:( Буду очень признателен за любую помощь!

Спасибо!

Ответы [ 5 ]

0 голосов
/ 23 февраля 2019

Если вы хотите, чтобы код для Loops / Arrays / Randoms работал вместе, вы можете использовать нижеприведенные комментарии с комментариями о том, что делает каждая строка ( Пример .NET Fiddle * )

public static void Main()
{
    // Pass in what range we want our randomly generated numbers to be in
    // In your case, between 1 - 1000 and we want to create 100 of them.
    //(See GenerateRandomNumbers())

    var random = GenerateRandomNumbers(1, 1000, 100);

    //Take our newly returned randomly created numbers and 
    //pass them to our GetMaxNumber method so it can find the Max number
    //See (GetMaxNumber())

    var result = GetMaxNumber(random);

    //We now have our max number; print it to the Console.

    Console.WriteLine("Max: " + result);
}

public static int GetMaxNumber(params int[] inputs)
{
    //Create a variable that will store the largest number we find in our array

    int max = inputs[0];

    //Iterate (loop) through all of the 100 values in our array that we passed in
    //Here we define "input" which will hold the value for each value in inputs as we check
    //if the value of input is greater than our current value of max. If it is greater than our
    //current value of max, then we need to update max to now be equal to the value of our input.
    //Note: it will do this comparison 100 times beginning with the first value in the inputs array

    foreach (var input in inputs)
    {
        if (input > max)
        {
            //input's value is greater than the current value of max; update max so that it is equal to the current value of input.

            max = input;
        }
        //no more code; return to top of foreach loop and set input to the next value in inputs
    }

    //When we get here, it means our foreach loop has completed going through and comparing all 100 values of inputs to see which value is the largest.
    //now return this value to Main()

    return max;
}

public static int[] GenerateRandomNumbers(int beginRange, int endRange, int maxNumbers)
{
    // Instantiate random number generator

    Random rnd = new Random();

    //Generate and display 

    int[] intArr = new int[maxNumbers];

    //Generate 100 numbers with numbers between 1 and 1000

    for (int i = 0; i < intArr.Length; i++)
    {
        int num = rnd.Next(beginRange, endRange);
        intArr[i] = num;
    }

    return intArr;
}
0 голосов
/ 23 февраля 2019

Хороший подход - инициализация переменной, в которой хранится ваш макс.Затем сгенерируйте случайное число в вашем итеративном блоке и, если оно больше вашего максимума, установите его в качестве нового максимума.

Random r = new Random();
int max = 0; //declare our max variable
for(int i = 0; i < 100; i++)
{
    int rand = r.Next(0, 1001);
    if(rand > max) //if the new random value is greater than our max, set max = rand
        max = rand;
}

Console.WriteLine(max); //Output the maximum value
Console.ReadLine(); 

Если вы хотите вывести каждое случайное значение, а затем вывести максимум из всех сгенерированных значений, просто измените приведенный выше код, выведя также rand в вашем цикле.

Надеюсь, это поможет!

0 голосов
/ 23 февраля 2019

Вы можете накапливать ваше случайное число в массиве, а затем с помощью функции Max массива вы можете найти максимальное значение

class Program
{
    public static void Main(string[] args)
    {
        Random rnd = new Random();
        int[] intArr = new int[100];

        for (int i = 0; i < intArr.Length; i++)
        {
            int num = rnd.Next(1, 1000);
            intArr[i] = num;
            Console.WriteLine(num);
        }

        Console.WriteLine();
        int maxNum = intArr.Max();
        Console.WriteLine("The max num is:" + maxNum);
        Console.ReadLine();
    }
}

Нажмите, чтобысмотреть онлайн демо

0 голосов
/ 23 февраля 2019

Я не уверен, вы спрашиваете так?

Random random = new Random();

int[] nums = new int[100];

// when for loop ends, nums are full of 100 numbers
for (int i = 0; i < nums.Length; i++)
{
    int newNum = random.Next(1, 1000);

    // show every number
    Console.WriteLine(newNum);

    nums[i] = newNum;
}

// get the max number
var maxNum = nums.Max();

Console.WriteLine(maxNum);
0 голосов
/ 23 февраля 2019

Вам нужно вызвать rnd.Next () внутри цикла.

Random rnd = new Random();
for (int i = 1; i <= 100; i++)
{
    int nums = rnd.Next(0, 1001);
    Console.WriteLine(nums);
}

Console.ReadLine(); 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...