3 回答

TA貢獻1934條經驗 獲得超2個贊
將數組索引存儲在變量中,以對其進行解析。
double a[] = new double[4];
int i = 0;
for (double PositionX = 0.0; PositionX <= 12000.0; PositionX += 3000.0)
{
a[i] = [yourvalue];
i++;
}
或者另一種方法是使用List.
List<int> a = new List<int>();
for (double PositionX = 0.0; PositionX <= 12000.0; PositionX += 3000.0)
{
a.Add([yourvalue]);
}

TA貢獻1821條經驗 獲得超6個贊
一種方法是使用索引:
double a[] = new double[4];
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.
a[index++]=PositionX ;
}
有很多方法可以做到這一點,也有很多聲明、初始化和遞增索引的方法。
你可以把它稍微翻轉一下,這樣會更健壯:
double a[] = new double[4];
int index=0;
double PositionX = 0.0;
for ( index=0; index<a.Length ; ++index )
{
a[index]=PositionX ;
PositionX += 3000.0
}

TA貢獻1871條經驗 獲得超13個贊
您的代碼有一些缺陷。在 C# 中創建數組的語法是:
double[] arrayName = new double[elmentCount];
(因此 [] 位于類型名之后,而不是變量名之后)
另外,您還會得到一個IndexOutOfRangeException
,因為 for 循環中的代碼將運行 5 次(0、3000、6000、9000 和 12000 均小于或等于 12000),但您的數組只有 4 個元素長。
只是為了向其他解決方案添加一些知識,您還可以使用 Linq 生成包含數字之間具有偶數空格的數組。我鼓勵您使用 linq,因為它非常棒。:)
double[] a = Enumerable.Range(0, 4).Select(x => x * 3000.0).ToArray();
Enumerable.Range 生成一個從 0 開始、包含 4 個元素的整數序列。Select 將每個整數與 3000.0 相乘,將其投影為雙精度型,然后 ToArray 將結果轉換為數組。
結果是一個包含 0.0、3000.0、6000.0、9000.0 的數組。如果您還想包含 12000.0,則只需將 4 更改為 5。
- 3 回答
- 0 關注
- 198 瀏覽
添加回答
舉報