可可触摸:rand()返回相同的字符串 [英] cocoa touch: rand() returning the same string

查看:70
本文介绍了可可触摸:rand()返回相同的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

-(void)randommoves
{

NSArray *possiblemoves =[NSArray arrayWithObjects:@"R ",@"R' ",@"L ",@"L' ",@"B ",@"B' ",@"F ",@"F' ",@"U ",@"U' ",@"D ",@"D' ", nil];
NSMutableString *finalmoves = [[NSMutableString alloc] init];
finalmoves = [NSMutableString stringWithCapacity:0]; 
[finalmoves retain];
int i = 0;
for (i=0; i<20; i++) {
    int r = rand() % 13;
    NSString *string = [possiblemoves objectAtIndex:r];
    [finalmoves appendString:string];
}
NSLog(@"%@",finalmoves);
[finalmoves release];
}

每次运行它,我都会得到完全相同的字符串 D'B B'D L'D'F'L'B'U'DD D'L'URBF D'B'

And every time I run it I get the EXACT same string "D' B B' D L' D' F' L' B' U' D D D' L' U R B F D' B' "

我想要做的就是给我每次运行时都要设置一个新动作

What I want it to do is give me a new move set every time I run it

我已经运行了至少30次,以确保它不是a幸的,而且确实返回了

I've ran this at least 30 times to make sure that it wasn't a fluke, and that it really WAS returning the same string, and sure enough, it is.

推荐答案

您需要确保首先为随机数生成器设定种子。

you need to make sure you seed your random number generator first.

在进入循环之前先做:

srand(time(NULL));

这篇关于可可触摸:rand()返回相同的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆