2017-05-12 51 views
0
int iterationMax = 1; 
double actualMax = 0; 
int A = 3; 

List<double> tmp = new List<double> { 400, 0, -300, 400, 600 ,300, 400, 
             1200, 900, 400, 1200, 1500}; 
List<double> listMax = new List<double>(); 
for (int i = 0; i < tmp.Count; i++) 
{ 
    if (iterationMax < A) // A == 3 
    { 
     if (tmp[i] > actualMax) 
     { 
      actualMax = tmp[i]; 
     } 
     iterationMax++; 
    } 
    else 
    { 
     listMax.Add(actualMax); 
     actualMax = 0; 
     iterationMax = 1; 
    } 
} 

Console.WriteLine("\nMaxs: "); 
foreach (double max in listMax) 
{ 
    Console.Write(max + ", "); 
} 

列表TMP持有= { 400,0,-300|400,600,300|400,1200,900|400,1200,1500}, 生產400, 600, 1200, 1200, 應該是400, 600, 1200, 1500。我不知道如何進入else語句來添加1500到列表。強制循環多一次?

我只想從每3個元素中獲得最大值。

+1

是不是有一個錯字? 'listMax.Add(aktualnyMax)'應該是'listMax.Add(actualMax)' – enkryptor

+0

是的,我是用不同的語言寫的,所以我不得不改變變量的名字 – quimak

+0

列表 tmp = new List (){400,0 ,-300,400,600,300,400,1200,900,400,1200,1500}; 列表 maxes = tmp.Select((x,i)=> new {value = x,index = i})GroupBy(x =>(int)(x.index/3))。Select(x = > x.Select(y => y.value).Max())。ToList(); – jdweng

回答

1

要快速解決您的代碼將是:

var A = 3; 

int iterationMax = 0; 
double actualMax = 0; 

List<double> tmp = new List<double> {400,0,-300,400,600,300,400,1200,900,400,1200,1500}; 
List<double> listMax = new List<double>(); 
for (int i = 0; i < tmp.Count; i++) 
{ 
    if (iterationMax < A) // A == 3 
    { 
     if (tmp[i] > actualMax) 
     { 
      actualMax = tmp[i]; 
     } 
     iterationMax++; 
    } 

    if (iterationMax == A) 
    { 
     listMax.Add(actualMax); 
     actualMax = 0; 
     iterationMax = 0; 
    } 
} 

Console.WriteLine("\nMaxs: "); 
foreach (double max in listMax) 
{ 
    Console.Write(max + ", "); 
} 

正如其他人說,從0開始iterationMax,並把這一elseif (iterationMax == A)

+0

非常感謝我正在尋找的東西。 – quimak

+0

第二個if相當於一個else –

+1

不可以,在兩個if語句的情況下,它們在每次迭代中都被檢查。當你使用if和else時,else只在if爲false時執行。這就是爲什麼在最後一次迭代中,我的其他人被跳過了。 – quimak

4

當需要對集合進行操作時,使用Linq會好很多倍。

index/3中使用GroupBy,因爲它是int以下每個項目將有不同的key。然後,爲每個組選擇的最大值:

var items = new int[] { 400, 0, -300, 400, 600, 300, 400, 1200, 900 }; 

var results = items.Select((item, index) => new { item, index }) 
        .GroupBy(item => item.index/3) 
        .Select(group => group.Max(item => item.item)); 
//400, 600, 1200 
0

在初始化和其他下設置iterationMax 0應該解決您的問題。

當前您的if結構只會檢查三個元素中的前兩個。由於1500是元素#3,所以不會被檢查。

0

問題是,當iterationMax達到3時,對溫度值不做任何處理,該循環丟失。

for (int i = 0; i < tmp.Count; i++) 
{ 
    if (tmp[i] > actualMax) 
    { 
     actualMax = tmp[i]; 
    } 
    iterationMax++; 

    if (iterationMax > A) 
    { 
     listMax.Add(actualMax); 
     actualMax = 0; 
     iterationMax = 1; 
    } 
} 
+0

是的,我不知道如何解決這個問題,但堆棧總是有幫助。我腦筋急轉彎 – quimak