0

我很难尝试每秒获取一个随机数并记录它以及它的运行平均值。

代码:

-(void)generateNumber:(NSTimer *)numberEachSecond
{        
    NSUInteger random = (arc4random() % 1000) +1;        
    NSMutableArray *listOfNumbers = [[NSMutableArray alloc]init];        
    NSNumber *number = [NSNumber numberWithInteger:random];        
    [listOfNumbers addObject:number];        

    // NSNumber *counter = 0;        
    for (NSNumber *generatedNumber in listOfNumbers) 
    {  
        NSLog(@"%@",generatedNumber);            
    }        
    NSLog(@"%@", listOfNumbers);        
}
4

2 回答 2

0

此代码将每秒生成一个随机数,并计算所有
生成的数字的平均值。

在.h

NSMutableArray *listOfNumbers;

在.m

-(void)viewDidLoad{
    listOfNumbers = [[NSMutableArray alloc]init];
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(generateNumber:) userInfo:nil repeats:YES];
}


-(void)generateNumber:(NSTimer *)numberEachSecond
{
NSUInteger random = (arc4random() % 1000) +1;
NSNumber *number = [NSNumber numberWithInteger:random];
[listOfNumbers addObject:number];
int total=0;
NSLog(@"%@",generatedNumber);  
for (NSNumber *generatedNumber in listOfNumbers)
{
    total=total + [generatedNumber intValue];
}

int average= total/[listOfNumbers count];
NSLog(@"average -- %d", average);
}
于 2013-05-16T06:41:36.963 回答
0

您生成随机数的逻辑似乎不错,但您不应该每次都将数组分配到该函数generateNumber中,它应该类似于,

alloc 数组某处一次或需要时,可能在viewDidLoad

listOfNumbers = [[NSMutableArray alloc]init]; //listOfNumbers should be instance variable

-(void)generateNumber:(NSTimer *)numberEachSecond 
{
    NSUInteger random = (arc4random() % 1000) +1;
    NSNumber *number = [NSNumber numberWithInteger:random];
    [listOfNumbers addObject:number];
}

你可以在函数之外的任何地方使用它,

NSLog(@"%@", listOfNumbers);
于 2013-05-16T05:36:17.430 回答