我在使用这段代码时遇到了一些麻烦:
for (long long int loop = 0; loop < 50000000; loop++)
{
srand( (unsigned)time(NULL) ); // set the seed
int r = abs(rand()); // stores the random seed for this loop
int res = loop + r - r * r / r; // random operations with the loop number and the random seed.
cout << "Loop number: " << loop << ". " << "Result: ";
cout << res << endl;
}//this was missing
Run Code Online (Sandbox Code Playgroud)
如果运行该代码,您可以在控制台中非常清楚地看到它的输出仅每隔几秒进行一次计算.这是怎么回事?每个循环的数量应该完全不同,因为它使用随机数进行计算.相反,数字会在每个x循环运行时更改,然后它似乎只会在这些时间之间增加,它实际上会进行数学运算.
我是否需要指定我希望循环等到一切都完成后再继续?
Arm*_*yan 12
因为你正在srand使用时间种子进行循环.time()粒度是以秒为单位,所以直到一秒钟过去它将返回相同的种子,因此返回相同的随机数.srand在循环之外做.
为rand函数播种的要点srand是生成的随机数序列随每个程序运行而不同.您只需要一个srand程序中的一个.
顺便说一句,rand()总是返回一个非负数,所以abs没用.虽然r可以0这样做但要小心,否则r可能会有不确定的行为.这样做r = rand()+1是安全的.
| 归档时间: |
|
| 查看次数: |
186 次 |
| 最近记录: |