How to generate a random int in C?

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

    This is a good way to get a random number between two numbers of your choice.

    #include 
    #include 
    #include 
    
        #define randnum(min, max) \
            ((rand() % (int)(((max) + 1) - (min))) + (min))
    
    int main()
    {
        srand(time(NULL));
    
        printf("%d\n", randnum(1, 70));
    }
    

    Output the first time: 39

    Output the second time: 61

    Output the third time: 65

    You can change the values after randnum to whatever numbers you choose, and it will generate a random number for you between those two numbers.

提交回复
热议问题