問題描述
每當我運行以下程序時,返回的值總是 6 或 13.
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?
謝謝.
順便說一下,如果我將 rand() 的范圍更改為 13 或 15,它就可以正常工作.
By the way, if I change the range of rand() to say 13 or 15 it works just fine.
推薦答案
我可以使用 Xcode 5 在 Mac OS X 10.9 上重現該問題 - 看起來它實際上可能是一個錯誤,或者至少是 的限制rand()
/srand()
在 OS X 10.9 上.
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.
我建議您使用 arc4random()相反,它比 rand()
效果更好,并且不需要隨機化種子:
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;
}
測試:
$ 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!