gpt4 book ai didi

c# - "Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"

转载 作者:行者123 更新时间:2023-11-30 19:16:43 31 4
gpt4 key购买 nike

为了创建一个包含 100 个介于 0 和 1 之间的随机数的列表,我在下面编写了收到错误的代码。

      public List<float> random()
{
List<float> storerandomvalues = new List<float>(100);
Random randomvalues = new Random();
float randomnum;
for (int counter = 0; counter < 100; counter++)
{
randomnum = 0f;
randomnum = randomvalues.Next(1);
storerandomvalues[counter]= randomnum; //the error
}
return storerandomvalues;
}

最佳答案

您正在创建空 storerandomvalues (没有任何项目)。 List<> 中的参数构造函数只是列表容量。

在您的情况下,最好的解决方案是使用数组而不是 List<> (因为在您的情况下,集合中的项目数是恒定的):

var storerandomvalues = new int[100];
Random randomvalues = new Random();
float randomnum;
for (int counter = 0; counter < storerandomvalues.Length; counter++)
{
randomnum = 0f;
randomnum = randomvalues.Next(1);
storerandomvalues[counter] = randomnum;
}
return storerandomvalues;

关于c# - "Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22130796/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com