2011-02-06 120 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