我希望打印20个随机数字。是否可以使用for
循环执行此操作;如果是的话,我该怎么办呢?
这是我目前的代码:
int[] randomNum = new int[20];
Random RandomNumber = new Random();
for (int i = 0; i < 20; i++)
{
randomNum[i] = RandomNumber.Next(1, 80);
}
foreach (int j in randomNum)
{
Console.WriteLine("First Number:{0}", j);
Thread.Sleep(200);
}
答案 0 :(得分:2)
只需循环数字生成,直到它生成一个新数字:
int[] randomNum = new int[20];
Random RandomNumber = new Random();
for (int i = 0; i < 20; i++)
{
int number;
do
{
number = RandomNumber.Next(1, 80);
} while(randomNum.Contains(number));
randomNum[i] = number;
}
foreach (int j in randomNum)
{
Console.WriteLine("First Number:{0}", j);
Thread.Sleep(200);
}
答案 1 :(得分:1)
根据你上次的评论,我会说:
for (int i = 0; i < 20; i++)
{
int num;
do
{
num = RandomNumber.Next(1, 80);
} while (randomNum.Contains(num));
randomNum[i] = num;
}
答案 2 :(得分:0)
为什么你使用数组呢?如果要打印随机数,可以写这个。
Random RandomNumber = new Random();
for (int i = 0; i < 20; i++)
{
int randomNum = RandomNumber.Next(1, 80);
Console.WriteLine("Number:{0}", randomNum);
Thread.Sleep(200);
}
答案 3 :(得分:-1)
你不需要randomNum。就这样做:
for (int i = 0; i < 20; i++)
{
Console.WriteLine("First Number:{0}", RandomNumber.Next(1, 80));
}
如果你想避免出版,请这样做:
List<int> intList = new List();
for (int i = 0; i < 20; i++)
{
int r = RandomNumber.Next(1, 80);
foreach(int s in intList) if(s!=r){
intList.Add(s);
Console.WriteLine("First Number:{0}", RandomNumber.Next(1, 80));
}else i--;
}