2013-05-18 81 views
-1

我正在创建这个游戏,其中涉及生成随机数。我必须添加一个选项(在游戏结束时)才能重新启动同一个游戏或创建一个新游戏。我怎样才能生成相同和不同的随机数字?相同和不同的随机数生成

+1

种子........... – Pubby

回答

4

保存您在srand()中使用的种子以生成相同的随机数,根据time()初始化种子以每次生成新序列。

2
/* srand example */ 
#include <stdio.h>  /* printf, NULL */ 
#include <stdlib.h>  /* srand, rand */ 
#include <time.h>  /* time */ 

int main() 
{ 
    printf ("First number: %d\n", rand()%100); 
    srand (time(NULL)); 
    printf ("Random number: %d\n", rand()%100); 
    srand (1); 
    printf ("Again the first number: %d\n", rand()%100); 

    return 0; 
} 

上面的代码是从这里找到函数srand例如:cplusplus.com

它同时显示了如何使用时间()和srand()函数来得到一个随机数,以及如何找回已生成再次编号。