简体   繁体   中英

rand() function behavior

I'm learning about the rand() function in C, as I want to use it to generate a random number in a range. However, I have a question about a part of the algorithm below.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    const MAX = 20, MIN = 1;
    srand(time(NULL));
    int randNumber = rand() % (MAX - MIN + 1) + MIN;
    printf("%d", randNumber);
    // yeu cau nhap so
    int duDoan;
    printf("Moi ban du doan con so:");
    scanf("%d", &duDoan);
    // chay vong lap kiem tra
    while(duDoan != randNumber) {
        printf("Ban da sai. Moi nhap lai:");
        scanf("%d", &duDoan);
    }
    printf("Ban da nhap dung. Dap an la: %d ", randNumber);

    return 0;
}

What confuses me here is why we have to add + MIN in this line:

rand() % (MAX - MIN + 1) + MIN;

If I leave it, what will the result be?

rand() is a number between 0 and RAND_MAX .

rand() % n is a number between 0 and n - 1. If you want a value from 0 to n, then you need rand() % (n+1) .

In your example (MAX - MIN + 1) is the span of integer values to generate, while MIN is the lower value. So for example where:

MIN = -10
MAX = 10

the span n :

n = (MAX - MIN + 1) = 21

so that:

rand() % n

yields values from 0 to 20, and

rand() % n - MIN

is -10 to +10. Without the +1, it would incorrectly be -10 to +9.

Note that where a statistically high quality random number is required restricting the span by the use of % is flawed and will introduce a bias when n is not a factor of RAND_MAX + 1 . In that case (int)(n * ((double)rand() / (double)RAND_MAX)) is a better solution, so you would have:

int randNumber = (int)((MAX - MIN) * ((double)rand() /
                                      (double)RAND_MAX)) + MIN ;

Note there is no +1 here because the range of (double)rand() / (double)RAND_MAX is 0 to 1, so multiplying by n gives 0 to n inclusive .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM