How to use the rand function to make numbers in a specific range?

前端 未结 4 925
深忆病人
深忆病人 2020-11-30 15:22

I would like to make random numbers in a specific range, like \"pick a random number between 18 and 35\"? How can I do that with the rand() function?

4条回答
  •  北海茫月
    2020-11-30 16:04

    If this is written in C, then you are pretty close. Compiling this code:

    #include 
    #include 
    
    int main() {
        int i;
        for (i = 0; i < 1000000; i++) {
            printf("%d\n", rand()%(35-18+1)+18);
        }
    }
    

    And running it in a pipeline produces this output:

    chris@zack:~$ gcc -o test test.c
    chris@zack:~$ ./test | sort | uniq -c
      55470 18
      55334 19
      55663 20
      55463 21
      55818 22
      55564 23
      55322 24
      55886 25
      55947 26
      55554 27
      55342 28
      55526 29
      55719 30
      55435 31
      55669 32
      55818 33
      55205 34
      55265 35
    

    The key is you forgot to add 1 -- the fencepost error.

    You can generalize this into a function:

    int random_between(int min, int max) {
        return rand() % (max - min + 1) + min;
    }
    

提交回复
热议问题