2012-07-25 80 views
0

我想显示在文本字段中键入的数字的每个因子以实现此目的我尝试使用数组。但我总是得到错误'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'。任何建议来消除这个错误?显示数字的因子

 NSMutableArray *array; 
     array = [NSMutableArray arrayWithCapacity:100]; 

     for (factorsNumber=1; factorsNumber<=number; factorsNumber++) { 
      if (number%factorsNumber == 0) { 
       [array addObject:[NSString stringWithFormat:@"%d", factorsNumber]]; 
      } 

     } 

     for (int i = 0; i <= [array count]; i++) { 
      factors.text = [NSString stringWithFormat:@"%d", i, [[array objectAtIndex:i] intValue]]; 
     } 
+2

'I <[数组数]' – beryllium 2012-07-25 11:50:59

+0

代码工作。但它只显示我的数组中的第一个对象。 – 2012-07-25 12:11:57

回答

1
for (int i = 0; i <= [array count]; i++) { 

应该是

for (int i = 0; i <= [array count] - 1; i++) { 

for (int i = 0; i < [array count]; i++) { 

一个n - 元素阵列的有效索引是0至n-1

+0

现在感谢它的工作。但不是给我所有的数字,它只给了我第一个。 – 2012-07-25 12:07:41

+0

可能因为因素编号<=素数。不应该是'因素编号<=编号? – 2012-07-25 12:09:27

+0

在我的代码中,它是! – 2012-07-25 12:10:24

1

在你的for循环,去除=,以便它读取:

for (int i = 0; i < [array count]; i++) 
1

你的问题就在这里:

for (int i = 0; i < [array count]; i++) { // < instead of <= 
    factors.text = [NSString stringWithFormat:@"%d", i, [[array objectAtIndex:i] intValue]]; 
}