简体   繁体   English

rand() 函数行为

[英]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.我正在学习 C 中的rand()函数,因为我想用它来生成一个范围内的随机数。 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:令我困惑的是为什么我们必须在这一行中添加+ MIN

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

If I leave it, what will the result be?如果我离开它,结果会怎样?

rand() is a number between 0 and RAND_MAX . rand()是一个介于 0 和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) . rand() % n是一个介于 0 和 n - 1 之间的数字。如果您想要一个从 0 到 n 的值,那么您需要rand() % (n+1)

In your example (MAX - MIN + 1) is the span of integer values to generate, while MIN is the lower value.在您的示例中(MAX - MIN + 1)是要生成的整数值的范围,而MIN是较低的值。 So for example where:例如,其中:

MIN = -10
MAX = 10

the span n :跨度n

n = (MAX - MIN + 1) = 21

so that:以便:

rand() % n

yields values from 0 to 20, and产生从 0 到 20 的值,以及

rand() % n - MIN

is -10 to +10.是 -10 到 +10。 Without the +1, it would incorrectly be -10 to +9.如果没有 +1,它将错误地为 -10 到 +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 .请注意,在需要统计高质量随机数的情况下,通过使用%来限制跨度是有缺陷的,并且当n不是RAND_MAX + 1的因子时会引入偏差。 In that case (int)(n * ((double)rand() / (double)RAND_MAX)) is a better solution, so you would have:在这种情况下(int)(n * ((double)rand() / (double)RAND_MAX))是一个更好的解决方案,所以你会有:

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 .注意这里没有 +1,因为(double)rand() / (double)RAND_MAX是 0 到 1,所以乘以 n 给出 0 到 n inclusive

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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