【问题标题】:How can I create a new number in an Array in a Specific position?如何在特定位置的数组中创建新数字?
【发布时间】:2022-11-21 22:45:54
【问题描述】:

我正在尝试将随机数保存在数组中

我试过这个机器人,它给了我一个错误(预期为常数值代码 CS0150)

`

int x = 0;

Random rnd = new Random();
int[] cards;
while (x != 5)
{
    cards =new int[x] { rnd.Next() };
    Console.WriteLine(cards[x]);
    x++;
}

`

【问题讨论】:

  • 欢迎来到 StackOverflow。如果收到错误消息,您需要在帖子中提供错误消息。实际上,如果您仔细阅读,该消息非常有用。您的主要问题是您每次在循环内新建数组。您需要在循环外创建一次。第二个是你的错误告诉你的,你可以指定初始化它的数量。如果数字不合适你会得到一个错误
  • 当前,您正在每次迭代中创建一个新数组。我假设你想在循环中使用 cards[x] = rnd.Next(),直接使用 int[] cards = new int[5]循环。
  • 但是我必须定义我想要的卡片数量吗?
  • 是的,至少对于一个数组。如果您想要动态的东西,请改用List<int>。但是,就您的代码而言,您只是添加了 5 个值,所以我不确定您是否需要它。

标签: c#


【解决方案1】:

目前,您在每次迭代时都创建了一个新数组。我假设你想在循环中使用 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++;
}

【讨论】:

    猜你喜欢
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 2010-10-05
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多