2013-11-25 58 views
4

这里是我的代码有:相同的随机数生成C++每次

int main(int argc, char** argv) { 

    int sleeptime = atoi(argv[1]);  
    int sleepCount = atoi(argv[2]); 

    int sleepTimeRandom = 1 + (rand() % (int)(sleeptime)); 
    int sleepCountRandom = 1 + (rand() % (int)(sleepCount)); 

    sleepTimeRandom = sleepTimeRandom * 1000; 

    DWORD id = GetCurrentProcessId(); 

    cout << "\n\nProcess with id " << id << " will sleep for " << sleepTimeRandom << " milliseconds\n"; 
    cout << "\n\nProcess with id " << id << " will sleep " << sleepCountRandom << " times \n"; 

当我打电话像

sleeper 4 4 

的exe我总是得到2000毫秒,4倍。为什么?

+1

提示:在兰特和播种读了随机数发生器。 – tletnes

+0

看起来没有电话[srand](http://www.cplusplus.com/reference/cstdlib/srand/)? – crashmstr

+0

需要调用srand()才能看到函数。查看http://stackoverflow.com/questions/4926622/how-to-generate-different-random-number-in-a-loop-in-c – OldProgrammer

回答

11

您必须为随机数生成器生成种子。 see here for an example

未seeded.c

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    printf ("Random not seeded: %d\n", rand()%10); 
    return 0; 
} 

未接种的输出

Random not seeded: 3 
Random not seeded: 3 
Random not seeded: 3 
Random not seeded: 3 
Random not seeded: 3 

seeded.c
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

int main() 
{ 
    srand(time(NULL)); 
    printf ("Random seeded: %d\n", rand()%10); 
    return 0; 
} 

接种的输出

Random fast seeded: 7 
Random fast seeded: 7 
Random fast seeded: 7 
Random fast seeded: 1 
Random fast seeded: 1 
Random fast seeded: 1 
Random fast seeded: 5 
Random fast seeded: 5 
Random fast seeded: 5 
Random fast seeded: 5 

fast-seeded.c

如果您希望能够每秒多次调用您的实用程序,您将必须为您的种子使用不同的来源,否则您仍然会得到一些重复的随机数。

这是一个使用纳秒而不是time()的示例,它只返回秒。

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

int main() 
{ 
    struct timespec ts; 
    clock_gettime(CLOCK_MONOTONIC, &ts); 

    /* using nano-seconds instead of seconds */ 
    srand((time_t)ts.tv_nsec); 

    printf ("Random fast seeded: %d\n", rand()%10); 
    return 0; 
} 

快种子输出

你可以在这里看到这些数字不进行分组不亚于前面的例子。

Random fast seeded: 9 
Random fast seeded: 6 
Random fast seeded: 5 
Random fast seeded: 6 
Random fast seeded: 1 
Random fast seeded: 1 
Random fast seeded: 9 
Random fast seeded: 4 
Random fast seeded: 3 
Random fast seeded: 2 

均匀分布的随机数

如果你有兴趣在均匀分布的随机数,你应该看到下面user3003631的答案。如果你实际上使用C++,那么我会推荐做随机数。 More information here too on this.

2

您需要使用time()函数为随机数生成器生成种子,以确保RNG以类似随机的方式运行。在开始生成随机数之前添加srand()调用。

+1

什么rkyser说,得到忍者:P –

8

还有随机效用这里的C++
如果你想不同的办法......可能更高质量
请原谅最低的解释

#include <iostream> 
#include <algorithm> 
#include <random> 

int random_test_200() 
{ 
    std::random_device rd; 
    uniform_int_distribution<int> ud(1,9); 
    mt19937 mt(rd()); 
    std::vector<int> v1; 
    for (int i = 0; i < 40; ++i) 
    { 
     auto x = ud(mt); 
     v1.push_back(x); 
    } 
} 
+2

这是最好的在这里回答,应该像瘟疫一样避免C rand库 – pyCthon