猿问

将 for 循环存储到数组中

我想将 for 循环存储到数组中,以便可以访问代码其他部分中的变量。


我尝试从类似的线程中解决几个解决方案,但无法让它们工作。我是 C# 和编码新手。谢谢你!


double a[] = new double[4]; 


for (double PositionX = 0.0; PositionX <= 12000.0; PositionX += 3000.0)

{

//I want the result of the for loop to be stored back into my array.

}


慕少森
浏览 148回答 3
3回答

撒科打诨

将数组索引存储在变量中,以对其进行解析。&nbsp; double a[] = new double[4];&nbsp;&nbsp; int i = 0;&nbsp; for (double PositionX = 0.0; PositionX <= 12000.0; PositionX += 3000.0)&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; a[i] = [yourvalue];&nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; }或者另一种方法是使用List.&nbsp; List<int> a = new List<int>();&nbsp; for (double PositionX = 0.0; PositionX <= 12000.0; PositionX += 3000.0)&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; a.Add([yourvalue]);&nbsp; }

达令说

一种方法是使用索引:double a[] = new double[4];&nbsp;int index=0;for (double PositionX = 0.0; PositionX <= 12000.0; PositionX += 3000.0){//I want the result of the for loop to be stored back into my array.&nbsp; &nbsp; a[index++]=PositionX ;}有很多方法可以做到这一点,也有很多声明、初始化和递增索引的方法。你可以把它稍微翻转一下,这样会更健壮:double a[] = new double[4];&nbsp;int index=0;double PositionX = 0.0;for ( index=0; index<a.Length ; ++index ){&nbsp; &nbsp; a[index]=PositionX ;&nbsp; &nbsp; PositionX += 3000.0}

慕桂英4014372

您的代码有一些缺陷。在 C# 中创建数组的语法是:double[]&nbsp;arrayName&nbsp;=&nbsp;new&nbsp;double[elmentCount];(因此 [] 位于类型名之后,而不是变量名之后)另外,您还会得到一个IndexOutOfRangeException,因为 for 循环中的代码将运行 5 次(0、3000、6000、9000 和 12000 均小于或等于 12000),但您的数组只有 4 个元素长。只是为了向其他解决方案添加一些知识,您还可以使用 Linq 生成包含数字之间具有偶数空格的数组。我鼓励您使用 linq,因为它非常棒。:)double[]&nbsp;a&nbsp;=&nbsp;Enumerable.Range(0,&nbsp;4).Select(x&nbsp;=>&nbsp;x&nbsp;*&nbsp;3000.0).ToArray();Enumerable.Range 生成一个从 0 开始、包含 4 个元素的整数序列。Select 将每个整数与 3000.0 相乘,将其投影为双精度型,然后 ToArray 将结果转换为数组。结果是一个包含 0.0、3000.0、6000.0、9000.0 的数组。如果您还想包含 12000.0,则只需将 4 更改为 5。
随时随地看视频慕课网APP
我要回答