如何每秒生成一个随机数并获得平均值?

时间:2013-05-16 05:30:20

标签: objective-c

我无法尝试每秒获得一个随机数记录以及它的平均运行时间。

代码:

-(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);        
}

2 个答案:

答案 0 :(得分:0)

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

将数组分配到某个地方或需要时,可能在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);

答案 1 :(得分:0)

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

中的.h

NSMutableArray *listOfNumbers;

int .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);
}