How to generate a random int in C?

后端 未结 27 2081
故里飘歌
故里飘歌 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;
    }
    
    0 讨论(0)
  • 2020-11-22 00:57

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

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
        #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.

    0 讨论(0)
  • 2020-11-22 00:57
    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    
    //generate number in range [min,max)
    int random(int min, int max){
        int number = min + rand() % (max - min);
        return number; 
    }
    
    //Driver code
    int main(){
        srand(time(NULL));
        for(int i = 1; i <= 10; i++){
            printf("%d\t", random(10, 100));
        }
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题