1. 程式人生 > >C語言生成隨機數

C語言生成隨機數

三個函式:

  • rand():返回 0-RAND_MAX 之間的一個隨機整數。
  • srand():和rand()函式配合使用,根據seed生成一個隨機起始點,然後rand()函式根據這個起始點產生隨機數。種子相同,生成的隨機數序列就相同。
  • time():生成一個數作為seed,保證每一次的seed都不一樣。

三者的關係就是time()生成一個數作為srand()的引數,然後再srand()為rand()生成一個數,最終就是rand()生成一個隨機數了。

-time()函式原型為time_t time(time_t *seconds);
1、引數為空指標時,返回值儲存在變數中。

#include <stdio.h>
    #include <time.h>
    int main ()
    {
      time_t seconds;
    seconds = time(NULL);
    printf("自 1970-01-01 起的小時數 = %ld\n", seconds/3600);

    return(0);
    }

2、引數為變數地址時,返回值可直接儲存在變數中。

#include <stdio.h>
    #include <time.h>
    int main ()
    {
    time_t seconds;
    time
(&seconds); printf("自 1970-01-01 起的小時數 = %ld\n", seconds/3600); return(0); }