简体   繁体   中英

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}. 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.

So, why are there TWO intervals?

{0,K} is understandable, but why is [0,1] necessary?

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). 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.

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.

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]. So for example, if you want a number between -2 and +2, you'd do something like this:

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. 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).

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