这段代码中的逻辑流可能有问题,但我想我会在这里发布它,看看它是否缺少我想要的东西。 (可能是,因为我目前对c#很新)。
此脚本应在高值和低值之间生成X量的随机数,并确保它不会生成两次相同的随机数。
目前,该脚本没有任何错误,但只创建一个随机数,无论定义的数量是多少'要创造的数字。
我尝试更改" int numberof = 11;对于一个公共的int,但显然打破了整个程序,我不知道为什么。
无论如何,支持表示赞赏。谢谢:))
代码:
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();
}
}
}
}
}