How to generate a random int in C?

后端 未结 27 2104
故里飘歌
故里飘歌 2020-11-22 00:31

Is there a function to generate a random int number in C? Or will I have to use a third party library?

27条回答
  •  长发绾君心
    2020-11-22 00:36

    Note: Don't use rand() for security. If you need a cryptographically secure number, see this answer instead.

    #include 
    #include 
    
    srand(time(NULL));   // Initialization, should only be called once.
    int r = rand();      // Returns a pseudo-random integer between 0 and RAND_MAX.
    

    Edit: On Linux, you might prefer to use random and srandom.

提交回复
热议问题