簡體   English   中英

如何在特定 position 的數組中創建新號碼?

[英]How can I create a new number in an Array in a Specific position?

我正在嘗試將隨機數保存在數組中

我試過這個機器人,它給了我一個錯誤(預期為常數值代碼 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]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM