Rand()%14只生成值6或13 [英] Rand() % 14 only generates the values 6 or 13
问题描述
每当我运行以下程序时,返回的值总是6或13。
#include< iostream>
#include< fstream>
#include< ctime>
#include< cstdlib>
using namespace std;
// void randomLegs();
// void randomPush();
// void randomPull();
// void randomMisc();
int main(int argc,const char * argv [])
{
srand(time(NULL));
// randomLegs();
cout<< rand()%14;
return 0;
}
我在今天和昨天已经运行了一百次。 / p>
任何人都可以告诉我我在做什么?
谢谢。
编辑:顺便说一下,如果我改变rand()的范围说13或15它工作正常。
我可以重现在Mac OS X 10.9与Xcode 5的问题 - 它看起来像它可能实际上是一个错误,或至少一个限制与 rand()
/ srand()
。
我建议您使用 arc4random(),它的工作原理比 rand()
好多了,并且不需要随机化种子: / p>
#include< iostream>
#include< cstdlib>
using namespace std;
int main(int argc,const char * argv [])
{
cout< (arc4random()%14)< endl;
return 0;
}
测试:
$ g ++ -Wall -O3 srand.cpp&& ./a.out
5
$ ./a.out
8
$ ./a.out
0
$ ./a.out
8
$ ./a.out
11
$ ./a.out
8
$ ./a.out
3
$ ./a.out
13
$ ./a.out
9
$
Whenever I run the following program the returned values are always 6 or 13.
#include <iostream>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
//void randomLegs();
//void randomPush();
//void randomPull();
//void randomMisc();
int main(int argc, const char * argv[])
{
srand(time(NULL));
//randomLegs();
cout << rand() % 14;
return 0;
}
I have run the program close to a hundred times during today and yesterday.
Can anyone tell me what I'm doing wrong?
Thank you.
EDIT: By the way, if I change the range of rand() to say 13 or 15 it works just fine.
I can reproduce the problem on Mac OS X 10.9 with Xcode 5 - it looks like it might actually be a bug, or at least a limitation with rand()
/srand()
on OS X 10.9.
I recommend you use arc4random() instead, which works a lot better than rand()
, and which doesn't require that you randomize the seed:
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, const char * argv[])
{
cout << (arc4random() % 14) << endl;
return 0;
}
Test:
$ g++ -Wall -O3 srand.cpp && ./a.out
5
$ ./a.out
8
$ ./a.out
0
$ ./a.out
8
$ ./a.out
11
$ ./a.out
8
$ ./a.out
3
$ ./a.out
13
$ ./a.out
9
$
这篇关于Rand()%14只生成值6或13的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!