我对以下代码有疑问:
#include <iostream>
#include <ctime>
int main(){
unsigned long int blob;
srand(time(0));
for(int counter = 0; counter <= 100; counter++) {
blob = rand() % 4000000000UL ;
std::cout << blob << std::endl;
}//for
system("pause");
return 0;
} //main
Run Code Online (Sandbox Code Playgroud)
在codepad.org上,它输出大的值,如
378332591
1798482639
294846778
1727237195
62560192
1257661042
Run Code Online (Sandbox Code Playgroud)
但是在Windows 7 64位上,它只输出小值(在VS11和Code :: Blocks上进行了测试编译)
10989
13493
13169
18581
17972
29
Run Code Online (Sandbox Code Playgroud)
在此先感谢帮助c ++学习者;)
rand()仅生成最多RAND_MAX的数字.
根据MSDN,在Windows上RAND_MAX只是32767,或(2**15 - 1)(请注意,这是根据C标准允许的最小RAND_MAX(此处链接到打开组基本规范,它基于C标准)) .
如果你想要更大的数字,你需要调用它更多次和比特移位,例如:
long long int my_big_random = rand() ^ (rand() << 15) ^ ((long long int) rand() << 30);
Run Code Online (Sandbox Code Playgroud)
(在键盘上的例子).