dimanche 28 avril 2019

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?




Aucun commentaire:

Enregistrer un commentaire