如何添加变量和数为42的数组并将其打印在数组的索引42中。谢谢你的帮助。我这样做但不能将变量添加到数字数组中,并且无法在数组中选择第42个变量
static NSMutableArray * numberArray ;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
int currentIndex;
int sumOfDigits;
numberArray = [NSMutableArray array];
for (int i=69999;i<80000;i++)
{
sumOfDigits= [self findTotalNumber:i];
if(sumOfDigits==42)
{
currentIndex++;
[numberArray addObject:[NSNumber numberWithInt:i]];
}
if(currentIndex>=42)
break;
}
NSLog(@"the number of elements in the array %lu",[numberArray count]);
}
-(void)print42thVariable
{
NSInteger index=41;
NSLog (@"42th variable of array is = %@", [numberArray objectAtIndex:index]);
}
-(int)findTotalNumber:(int)number
{
int digit,sum=0, temp;
temp = number;
while(temp > 0)
{
digit = temp%10;
sum += digit;
temp = temp/10;
}
NSLog(@"Sum of digits of %i = %i",number,sum);
return number;
}
答案 0 :(得分:0)
如果你想找到数字总和为42的第42个数字,那么你可以直接替换
NSLog(@"the number of elements in the array %lu",[numberArray count]);
带
NSLog(@"%i", [numberArray objectAtIndex:41])
这将打印出第42个元素。
答案 1 :(得分:0)
似乎是微不足道的,你写了print42thVaribale
,但你从来没有打电话给它。
在Log ??
NSLog(@"the number of elements in the array %lu",[numberArray count]);
[self print42thVariable];
还需要更多修正,
-(int)findTotalNumber:(int)number
{
int digit,sum=0, temp;
temp = number;
while(temp > 0)
{
digit = temp%10;
sum += digit;
temp = temp/10;
}
NSLog(@"Sum of digits of %i = %i",number,sum);
return sum; //Needs to be sum and not number
}
这应该不是问题,而是初始化变量的好习惯。
int sumOfDigits = 0;