Problems encountered in generating random numbers for C programs

Source: Internet
Author: User

I've had this problem a long time ago, and today I stepped on the pit ...

If you want to generate random numbers in the C language, you need to call RAND ()

    The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.
#include <stdio.h>#include <stdlib.h>int main(){    int0;    for05;temp++)    {        printf("%d\t",rand());    }    printf("\n");    return0;}

I am (‵o′) convex every time the same result, you told me you are random number? I X

Here you need to initialize ... It is best to use the current time to seed and then "feed" the Srand () function to initialize the rand (). Each time the program is called, because the time is different, the seed is different, randomly can always get different random numbers.

#include <stdio.h>#include <stdlib.h>int main(){    int0;    srand(time(NULL));    for05;temp++)    {        printf("%d\t",rand());    }    printf("\n");    return0;}

Some time ago also see DSAA How to write a rand (), and was indefinitely shelved ...

Problems encountered in generating random numbers for C programs

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.