How to generate a random int in C?

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

    C Program to generate random number between 9 and 50

    #include 
    #include 
    
    int main()
    {
        srand(time(NULL));
        int lowerLimit = 10, upperLimit = 50;
        int r =  lowerLimit + rand() % (upperLimit - lowerLimit);
        printf("%d", r);
    }
    

    In general we can generate a random number between lowerLimit and upperLimit-1

    i.e lowerLimit is inclusive or say r ∈ [ lowerLimit, upperLimit )

提交回复
热议问题