显示数字的因子

时间:2012-07-25 11:47:53

标签: objective-c arrays xcode factorization

我想显示在文本字段中输入的数字的每个因子来实现这一点我尝试使用数组。但我总是收到错误'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]];
        }

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

在for循环中,删除=,使其显示为:

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

答案 2 :(得分:1)

你的问题在这里:

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