【发布时间】:2026-01-23 14:25:01
【问题描述】:
我有这个数组,它有五个介于 1 到 10 之间的随机数:
NSMutableArray *arrayOfNumbers = [NSMutableArray array];
for (int x = 0; x < 5; x++)
{
[arrayOfNumbers addObject: [NSNumber numberWithInt: arc4random()%10]];
}
NSLog(@"%@",arrayOfNumbers);
我想把前两个和最后两个对象加在一起。如果它们加在一起,我想返回 2。如果它们不加在一起,我想检查第二个和第三个对象是否加起来最后两个对象。所以基本上如果我有数组 [2,3,9,4,1] 那么我想检查一下 2+3=4+1。在这种情况下,是的,所以我会返回 2。在这个数组中 [2,3,6,4,5] 2+3!=4+5 所以我们将继续检查 3+6=4+5 并且因为是我们返回 2。现在,如果没有两个对象相加时可以等于 [0,1,2,3,4],那么我们将返回 -1。
这是我到目前为止所做的:
int lastValue = [arrayOfNumbers count];
int secondlastValue = [arrayOfNumbers count] - 1;
int firstValue = 0;
int secondValue = 1;
int i;
for (i = 0; i < [arrayOfNumbers count]; i++) {
int one = [[arrayOfNumbers objectAtIndex:firstValue + i] integerValue];
int two = [[arrayOfNumbers objectAtIndex:secondValue + i] integerValue];
int secondtolast = [[arrayOfNumbers objectAtIndex:secondlastValue] integerValue];
int last = [[arrayOfNumbers objectAtIndex:lastValue] integerValue];
if (one + two == secondtolast + last) {
NSLog(@"2: Because %i + %i = %i + %i",firstValue,secondValue,secondlastValue,lastValue);
break;
} else {
NSLog(@"-1");
}
}
但由于某种原因,它崩溃了...任何帮助将不胜感激。谢谢!
编辑:这是错误*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]'
编辑 2: 这些是我的 NSLog 的
if ((one + two) == totalOfLastValues) {
NSLog(@"2: Because %@ + %@ (%i) = %@ + %@",arrayOfNumbers[i],arrayOfNumbers[i+1],one+two,[arrayOfNumbers objectAtIndex:[arrayOfNumbers count] - 2],[arrayOfNumbers lastObject]);
break;
} else {
NSLog(@"-1: Because %@ + %@ (%i) != %@ + %@",arrayOfNumbers[i],arrayOfNumbers[i+1],one+two,[arrayOfNumbers objectAtIndex:[arrayOfNumbers count] - 2],[arrayOfNumbers lastObject]);
}
【问题讨论】:
-
您的代码看起来像是生成了超出范围的索引异常。为什么要遍历数组并将 i 添加到 firstvalue 和 secondvalue?您应该设置断点并单步执行您的代码,以便了解它的行为方式。
标签: ios iphone objective-c arrays