C ++ for循环不等待完成?

时间:2014-12-18 11:57:30

标签: c++ loops for-loop

我在使用此代码时遇到了一些问题:

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

如果运行该代码,您可以在控制台中非常清楚地看到它的输出仅每隔几秒进行一次计算。发生了什么事?每个循环的数字应该完全不同,因为它使用随机数进行计算。相反,数字会在每次运行的x循环中发生变化,然后它似乎只会在实际数学运算之间增加。

我是否需要指定我希望循环等到一切都完成后再继续?

2 个答案:

答案 0 :(得分:12)

因为你在循环中使用时间种子进行srandtime()的粒度是以秒为单位,所以直到一秒钟过去它将返回相同的种子,因此返回相同的随机数。在循环外做srand

使用srand播种rand函数的关键是生成的随机数序列随每个程序运行而不同。您的计划中只需要一个srand

顺便说一下,rand()总是会返回一个非负数,因此abs无用。但请注意,r可以是0,并且除以r,这可能具有未定义的行为。确保r = rand()+1安全。

答案 1 :(得分:1)

您的种子在同一秒内是相同的,因此该种子的随机数将是相同的。你可以尝试取出它。

srand( (unsigned)time(NULL) ); // set the seed
for (long long int loop = 0; loop < 50000000; loop++)
{
    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;
}

干杯

相关问题