How to generate a random int in C?

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

    My minimalistic solution should work for random numbers in range [min, max). Use srand(time(NULL)) before invoking the function.

    int range_rand(int min_num, int max_num) {
        if (min_num >= max_num) {
            fprintf(stderr, "min_num is greater or equal than max_num!\n"); 
        }
        return min_num + (rand() % (max_num - min_num));
    } 
    

提交回复
热议问题