如何在for循环外更改int

时间:2014-02-08 10:13:25

标签: ios iphone objective-c arrays

我编写了一个算法,我希望它使用随机数组,并在该数组中添加第一个和最后一个数字。示例:我的数组是[0,5,3,8,2,4,7,9,6,1]并且我的算法应该检查1 + 5 = 6 + 0,并且因为它不是,它应该检查是否5 + 3 = 9 + 6,然后如果3 + 8 = 7 + 9,依此类推......

我的第一个for循环是检查数组中最后一个数字的位置。问题是int totalOfLastValues仅在for循环内更新,因此最后的值甚至没有递增。例如,在数组[0,5,3,8,2,4,7,9,6,1]中,0 + 5 = 6 + 1不成立,因此检查5 + 3 = 6 + 1而不是检查5 + 3 = 9 + 6。

在我的.h

@interface FirstViewController : UIViewController

@end
int totalOfLastValues;
int end;
int almost;

在我的.m

-(void) numberAlgorithm {
    NSMutableArray *arrayOfNumbers = [NSMutableArray array];
    for (int x = 0; x < 10; x++)
    {
        int randomNumbers = arc4random_uniform(10);
        [arrayOfNumbers addObject: [NSNumber numberWithInteger: randomNumbers]];
    }
    NSLog(@"%@",arrayOfNumbers);

    int lastValue = [arrayOfNumbers count]-1;
    for (int p = lastValue; p > 2; p--) {
        end = [arrayOfNumbers[0 + p] integerValue];
        almost = [arrayOfNumbers[(0-1) + p] integerValue];
        totalOfLastValues = end + almost;            
    }

    int mostRecentValue  = [arrayOfNumbers[0] integerValue];
    for (int i = 1; i < [arrayOfNumbers count]-2; i++) {
        int one = mostRecentValue;
        int two = [arrayOfNumbers[i] integerValue];
        mostRecentValue = two;

        if ((one + two) == totalOfLastValues) {
            NSLog(@"2: Because %@ + %@ = %@ + %@",arrayOfNumbers[i-1],arrayOfNumbers[i],arrayOfNumbers[(0-1) + lastValue],arrayOfNumbers[0 + lastValue]);
            break;
        } else {
            NSLog(@"-1: Because %@ + %@ != %@ + %@",arrayOfNumbers[i-1],arrayOfNumbers[i],arrayOfNumbers[(0-1) + lastValue],arrayOfNumbers[0 + lastValue]);
        }
    }
}

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

据我所知,我认为这可能对你有所帮助:

int arrLength = (int)[arrayOfNumbers count];
for (int x = 0; x < arrLength/2; x++) {
    if(x < arrLength-1) {
        NSLog(@"%i + %i compare %i + %i", [arrayOfNumbers[x] intValue], [arrayOfNumbers[x+1] intValue], [arrayOfNumbers[(arrLength-1) - x] intValue], [arrayOfNumbers[(arrLength-2) - x] intValue]);
    }
}

我得到的输出

2014-02-08 04:36:54.517 Test[54846:70b] (
    3,
    5,
    3,
    6,
    4,
    4,
    6,
    6,
    5,
    6
)
2014-02-08 04:36:54.518 Test[54846:70b] 3 + 5 compare 6 + 5
2014-02-08 04:36:54.519 Test[54846:70b] 5 + 3 compare 5 + 6
2014-02-08 04:36:54.520 Test[54846:70b] 3 + 6 compare 6 + 6
2014-02-08 04:36:54.520 Test[54846:70b] 6 + 4 compare 6 + 4
2014-02-08 04:36:54.521 Test[54846:70b] 4 + 4 compare 4 + 4