亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 for 循環存儲到數組中

將 for 循環存儲到數組中

C#
慕少森 2023-07-09 15:10:57
我想將 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.}
查看完整描述

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]);

  }


查看完整回答
反對 回復 2023-07-09
?
達令說

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

}


查看完整回答
反對 回復 2023-07-09
?
慕桂英4014372

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。


查看完整回答
反對 回復 2023-07-09
  • 3 回答
  • 0 關注
  • 198 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號