在婴儿级别描述它,我是初学者......static void Main(string[] args){ string[] Names = { "Erik", "Levente", "Noel", "Áron", "Krisztián", "Kristóf", "Bence", "Roland", "Máté", "László", "Bálint" , "Regina", "Brigitta", "Gréta", "Hédi", "Hanna", "Boglárka", "Jázmin", "Réka", "Alexandra", "Rebeka", "Lili", "Luca", "Zsófi"}; List<string> alreadyUsed = new List<string>(); Random r = new Random(); while (alreadyUsed.Count < Names.Length) { int index = r.Next(0, Names.Length); if (!alreadyUsed.Contains(Names[index])) alreadyUsed.Add(Names[index]); Console.WriteLine("The 1st Winner is: " + Names[r.Next(0, Names.Length - 1)]); } Console.ReadKey(true);}
2 回答
繁花如伊
TA贡献2012条经验 获得超12个赞
如果您只想显示没有重复的结果,请尝试:
while (alreadyUsed.Count < Names.Length)
{
int index = r.Next(0, Names.Length);
if (!alreadyUsed.Contains(Names[index]))
{
alreadyUsed.Add(Names[index]);
Console.WriteLine("The 1st Winner is: " + Names[index]);
}
}
请注意,在Console.WriteLine我使用当前添加的项目Names[index]而不是Names[r.Next(0, Names.Length - 1)]
茅侃侃
TA贡献1842条经验 获得超21个赞
也许这个版本增加了一些可读性:
while (alreadyUsed.Count < Names.Length)
{
var notUsedYet = Names.Except(alreadyUsed).ToArray();
var index = r.Next(0, notUsedYet.Length);
alreadyUsed.Add(notUsedYet[index]);
Console.WriteLine("The 1st Winner is: " + notUsedYet[index]);
}
- 2 回答
- 0 关注
- 201 浏览
添加回答
举报
0/150
提交
取消