2011-02-06 141 views
0

我有一個小問題,下面的代碼(C#),它循環以爲陣列,它然後檢查USER_ID有user_post大於50,它然後寫USER_ID,預期的結果是循環雖然數組然後如果然後輸出結果?

12 
13 

但實際輸出是

12 
12 
12 

最新的代碼是什麼問題?我嘗試了一個標準的循環,但不能正確嗎?

int[] user_id = new int[64]; 
int[] group_id = new int[64]; 
int[] user_post = new int[64]; 

//user 55 
user_id[0] = 10; 
group_id[0] = 8; 
user_post[0] = 4; 

//user56 
user_id[1] = 11; 
group_id[1] = 2; 
user_post[1] = 15; 

//user57 
user_id[2] = 12; 
group_id[2] = 2; 
user_post[2] = 55; 

//user58 
user_id[3] = 13; 
group_id[3] = 2; 
user_post[3] = 56; 

foreach (int i in group_id) 
{ 
    if (group_id[i] == 2) 
     if (user_post[i] > 50) 
      Console.WriteLine(Convert.ToString(user_id[i])); 
} 

Console.WriteLine("Press any key too continue..."); 
Console.ReadLine(); 
// continue... 
+2

Hmmmm,這不是一個不好的問題,但我認爲通過學習使用IDE中的調試功能,您可以獲得比從SO更快的答案。 – Juliet 2011-02-06 21:51:07

+0

+1完全同意..人們正在採取SO作爲替代調試器 – 2011-02-06 21:55:31

回答

1

因爲你有一個if語句,只有2

if (group_id[i] == 2) 

檢查,其中爲「i」是不是反而不是從foreach循環的元素。 和項目在2 & 3位有2組ID所以送花兒給人這樣的結尾:

if (group_id[8] == 2) //false 
if (group_id[2] == 2) //true 
if (group_id[2] == 2) //true 

的而不是模糊的代碼,你應該有你的循環是這樣的:

for(int i = 0 ; i< 64 ; i++) 
{ 
    if (group_id[i] == 2) 
    { 
     if (user_post[i] > 50) 
     Console.WriteLine(Convert.ToString(user_id[i])); 
    } 

} 
0
foreach (int i in group_id) 

是錯誤的,您必須使用:

for(int i = 0; i < group_id.Length; i++) 

,因爲前者使用group_id中的值作爲數組的索引。

順便說一句,我建議你創建一個類,例如Info像:

class Info 
{ 
    public int GroupId {get; set;}; 
    public int UserId {get; set;}; 
    public int PostId {get; set;} 
} 

這將允許您創建只有一個陣列(即Info[]),並避免由於3個陣列的兩種不同長度可能出現的錯誤......

0

你循環錯陣列周圍與每個陳述。你應該使用常規的語句,而不是像這樣的循環:

for (int i = 0;i < user_post.Length; i++) 
    { 
     if (user_post[i] > 50 && group_id[i] == 2) 
     { 
      Console.WriteLine(Convert.ToString(user_id[i])); 
     } 
    } 
0
在你的foreach語句

i需要存儲在您的GROUP_ID數組中的值 - 8,2,2,2

在你if和輸出語句,你正在使用這個值作爲索引到數組

所以,你if報表最終做此:

if(group_id[8])... 
if(group_id[2])... 
if(group_id[2])... 
if(group_id[2])... 

您只是在檢查陣列中的元素8和2。

使用for遍歷數組索引

0

for語法迭代如下:

for (int i = 0; // incremental variable 
    i < 100; // determining a limit 
    ++i)  // increment the variable 

雖然foreach是這樣工作的:

foreach (var element  // the element itself, not an index 
     in 
     elementCollection) // iterating through the collection