我试图在数组中保存随机数
我已经尝试了这个bot,它给了我一个错误(一个常量值是预期代码CS0150)
int x = 0;
Random rnd = new Random();
int[] cards;
while (x != 5)
{
cards =new int[x] { rnd.Next() };
Console.WriteLine(cards[x]);
x++;
}
当前,每次迭代都创建一个新的数组。我假设您希望cards[x] = rnd.Next()
在循环内,并且int[] cards = new int[5]
直接在循环之前:
int x = 0;
Random rnd = new Random();
int[] cards = new int[5];
while (x != 5)
{
cards[x] = rnd.Next();
Console.WriteLine(cards[x]);
x++;
}
我已经制作了一个列表而不是数组,所以我可以使用未定义的卡片数量'
int x = 0;
Random rnd = new Random();
List<int> cards = new List<int>();
while (x != 5)
{
cards.Add(rnd.Next());
Console.WriteLine(cards[x]);
x++;
}
——不是为了点
如果你要使用List<>
,那么使用Count
属性:
Random rnd = new Random();
List<int> cards = new List<int>();
while (cards.Count < 5)
{
cards.Add(rnd.Next());
Console.WriteLine(cards[cards.Count-1]);
}
如果你打算使用Array
,那么使用for
循环和Length
属性:
Random rnd = new Random();
int[] cards = new int[5];
for(int x=0; x<cards.Length; x++)
{
cards[x] = rnd.Next();
Console.WriteLine(cards[x]);
}