mercredi 26 avril 2017

Random number generator loop isnt working [duplicate]

This question already has an answer here:

Theres probably something wrong with the flow of logic in this code, though i thought i would post it here to see if its something simple i am missing. (It probably is, as i am currently quite new to c#).

This script is supposed to generate X amount of random numbers between a High value and a Low value, as well as ensuring it does not generate the same random number twice.

Right now, the script is not having any errors, but is only creating one random number, regardless of the defined 'amount' of numbers to create.

I tried changing "int numberof = 11; to a public int, but apparently that breaks the entire program and i dont know why.

Anyway, support is appreciated. Thanks :)

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Randomnumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            int numberof = 11;
            Console.WriteLine("Numbers Generated:");
            while (numberof > 0) //Repeats this loop once for each "numberof". (until the number hits zero)
            {
                numberof = numberof - 1;
                generatenewnumber(); //Calls the function
            }
            if (numberof == 0)
            {
                Console.ReadLine(); // Here so the program doesnt instantly close
            }
        }

        static void generatenewnumber()
        {
            var rng = new Random();
            int lowrange = 0;
            int highrange = 50;
            int numberof = 11;
            int number = rng.Next(lowrange, highrange); //Sets the number to a random number between the high and low values.
            var generated = new List<int>(); // Creates a list of numbers that have been generated already to prevent double-ups.
            while (numberof > 0)
            {
                if (generated.Contains(number)) // Checks if the rg'd number has already been made.
                {
                    generatenewnumber(); //Calls the function above
                }
                else
                {
                    numberof = numberof - 1;
                    generated.Add(number); // Adds the genereated number to the list.
                    Console.WriteLine(number); // Prints the number. 
                    Console.ReadLine();
                }
            }
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire