2016-01-13 29 views
-4

無法從雙轉換爲int,我的計劃是試圖減去從它的列表,並將結果添加到一個新的列表,但出於某種原因即時得到這個錯誤:C#「不能隱式地從雙轉換爲int」

List<double> test = new List<double>(); 
List<double> theOneList = new List<double>(); 
theOneList = wqList.Concat(rList).Concat(eList).ToList(); 
theOneList.Add(0); 

theOneList.OrderByDescending(z => z).ToList(); 
for (double i = 0; i < 5; i++) 
{ 
    test.Add(theOneList[i + 2.0] - theOneList[i + 3.0]); 
    Console.WriteLine(test[i]); 
} 

摘要:當我打印出來的清單即時得到INT的,而不是雙倍的,我已經失去了這個名單上的精度,因爲「詮釋」聲明

+0

不能使用雙值作爲一個表的或數組的索引。有沒有你不使用整數的原因? – Jules

+0

哦,jeez,也許是因爲我想把值保持爲double?通過使用(int)即時獲得我的答案作爲整體數字,從而失去了精度 – AdanChristo

+0

您的列表的通用類型和您的索引方式根本沒有關係。你可以有一個字符串列表或者double列表等等,但是你總是需要用一個int來索引它......對索引列表的第1.5個元素沒有任何意義:) –

回答

5

列表索引應int型的,但你聲明它作爲你的循環中的double

for (double i = 0; i < 5; i++) 

更改i類型int和使用不i + 2.0i + 2等。

1

你不能索引一個雙數的數組。您需要使用整數來執行該操作:

for (int i = 0; i < 5; i++) 
    { 
     test.Add(theOneList[i + 2] - theOneList[i + 3]); 
     Console.WriteLine(test[i]); 
    } 
-1

邏輯中存在多個錯誤;

List<double> test = new List<double>(); 
    List<double> theOneList = wqList.Concat(rList).Concat(eList).ToList(); 
    theOneList.Add(0); 

    theOneList = theOneList.OrderByDescending(z => z).ToList(); // you need to set the list after ordering; or the old list will not change 
    for (int i = 0; i < 5; i++) // change variables to integer, do you know that at least 8 values exists in theOneList? 
    { 
     test.Add(theOneList[i + 2] - theOneList[i + 3]); 
     Console.WriteLine(test[i]); 
    } 
0

這是基於這個MSDN page: Using Indexer

一般來說,索引的聲明看起來是這樣的:

public int this[int index] // Indexer declaration 
{ 
    // get and set accessors 
} 

正如你所看到的,索引被聲明爲一個整數值。因此,有2種適當的方法可以讓你的代碼工作:

  1. 更改叫iintdouble變量的數據類型。就我允許的估計而言,這將是最佳做法。
  2. 您將i的值轉換爲int,然後再將其用作索引,但我不建議這樣做。

    test.Add(theOneList[(int)i + 2] - theOneList[(int)i + 3]); 
    
相關問題