How to generate a random int in C?

后端 未结 27 2457
故里飘歌
故里飘歌 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:53

    Try this, I put it together from some of the concepts already referenced above:

    /*    
    Uses the srand() function to seed the random number generator based on time value,
    then returns an integer in the range 1 to max. Call this with random(n) where n is an integer, and you get an integer as a return value.
     */
    
    int random(int max) {
        srand((unsigned) time(NULL));
        return (rand() % max) + 1;
    }
    

提交回复
热议问题