简体   繁体   English

简单的Rand()函数

[英]Simple Rand() function

Write a function with the following prototype. 使用以下原型编写函数。 int getRandomIntFrom0ToK(int K) The function calls the random number generator that generates a random value uniformly distributed in interval [0,1] and returns, for positive integer K, a random number uniformly distributed over integers {0,1,2,...K}. int getRandomIntFrom0ToK(int K)该函数调用随机数生成器,该生成器生成均匀分布在间隔[0,1]中的随机值,并为正整数K返回均匀分布在整数{0,1,2,上的随机数。 ..K}。 Write a program to test the function, which shows that the generated random integers by your function hit each number in {0,1,2,...K} with approximately equal probability. 编写程序测试该函数,该函数将显示函数生成的随机整数以大约相等的概率命中{0,1,2,... K}中的每个数字。

So, why are there TWO intervals? 那么,为什么会有两个间隔?

{0,K} is understandable, but why is [0,1] necessary? {0,K}是可以理解的,但是为什么[0,1]是必需的?

I have no idea what I'm doing so far: 我不知道到目前为止我在做什么:

#include <stdio.h>

int getRandomIntFrom0toK(int K)
{
    int i=0;

    printf("enter k:");
    scanf("%d",&K);

    while (i<K)
    {
        int num=(rand()%(K-1)+1);
        printf("%d\n",num);
        i++;
    }
}

int main(void)
{
    int result=getRandomIntFrom0toK(1+rand()%(1));
    return 0;
}

The interval [0,1] is typically what a random number generator might return if it's returning a "real" number (ie a float, rather than an int). 间隔[0,1]通常是随机数生成器返回“实数”(即浮点数而不是整数)时可能返回的时间间隔。 This isn't what you want , it's what you're given as a random number generator. 这是不是你想要的,这就是你什么作为一个随机数发生器。 Your task is to transform the result into what you want, which is an integer between 0 and K. 您的任务是将结果转换为所需的值,该值是0到K之间的整数。

As it happens, the C rand() function returns an int rather than a float, so you probably want to divide by RAND_MAX to get the same effect if you're testing your code. 碰巧的是,C rand()函数返回一个int而不是浮点数,因此如果您正在测试代码,则可能要除以RAND_MAX以获得相同的效果。

It's easy enough to transform the result of this generator into any interval that you want, by multiplying the result by K to transform it into the range [0,K], and then adding an offset L to shift it into the range [L,L+K]. 通过将结果乘以K将其转换为[0,K]范围,然后加上偏移量L将其转换为[L, L + K]。 So for example, if you want a number between -2 and +2, you'd do something like this: 因此,例如,如果您想要一个介于-2和+2之间的数字,则可以执行以下操作:

float x = rand() / (float) RAND_MAX; /* x is between 0 and 1 */
x = x * 4; /* x is now between 0 and 4 */
x = x - 2; /* x is now between -2 and 2 */

In your case, you want an integer, not a float, between 0 and K. So once you've done the transformation, you can round to the nearest integer. 在您的情况下,您需要一个0到K之间的整数,而不是浮点数。因此,一旦完成转换,就可以舍入到最接近的整数。 But you'll need to be careful to pick your range correctly so that 0 and K are as likely as any of the intermediate integers, and so that you don't ever get a value outside of the range (eg -1 or K+1). 但是,您需要小心选择正确的范围,以使0和K与任何中间整数一样大,并且永远不会获得超出范围的值(例如-1或K + 1)。

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

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