Use C language to generate random numbers

Source: Internet
Author: User
Tags ranges

In C language, the rand () function can be used to generate random numbers, but this is not a real random number. It is a pseudo-random number. It is based on a number. We can call it a seed, A coefficient calculated based on a recursive formula. When the number of series is large, it is in line with the normal announcement, which is equivalent to generating a random number, but this is not a real random number, after the computer starts up normally, the seed value is fixed. Unless you break the system, C provides the srand () function to change the seed value, its prototype is void srand (int ).

We may all know the random function random in C language, but the random function is not ansi c standard. Therefore, the random function cannot be compiled by gcc, vc, or other compilers.

Rand () returns a random value ranging from 0 to RAND_MAX. Returns a random value between 0 and RAND_MAX. RAND_MAX is defined in stdlib. h, (its value is at least 32767) the result of my operation is an indefinite number. It depends on the variable type you define. If it is int, It is 32767. Before calling this function to generate a random number, you must use srand () to set the random number seed. If no random number seed is set, rand () will automatically set the random number seed to 1. Generally, the for statement is used to set the number of seeds. For details, see the example below.

 

How can we generate unforeseen random sequences?
Srand (unsigned int) (time (NULL) is a method, because the time of each running program is different.

Usage of the random number generator provided in the C language: the C compiler now provides a function based on the ANSI standard pseudo random number generator to generate random numbers. They are the rand () and srand () functions. The two functions work as follows:

1) First, provide a seed for srand (). It is of the unsigned int type and its value ranges from 0 ~ 65535;

2) then call rand (), which returns a random number (between 0 and 32767) based on the seed value provided to srand)

3) call rand () multiple times as needed to continuously obtain new random numbers;

4) at any time, srand () can be provided with a new seed to further "randomize" the output results of rand.
Below is 0 ~ Random Number program between 32767:

# Include <stdlib. h> # include <stdio. h> # include <time. h> // use the current clock as the seed void main (void) {int I; srand (unsigned) Time (null); // initialize the random number for (I = 0; I <10; I ++) // print out 10 random numbers printf ("% d \ n", Rand ());}

 

According to the above program, it is easy to get 0 ~ Random number between 1:

#include <stdlib.h>#include <stdio.h>#include <time.h> main( ){int i;srand( (unsigned)time( NULL ) );         for( i = 0; i < 10;i++ )            printf( "%5.2f\n", rand()/32767.0);}

 

Generation 1 ~ The random number between 100 can be written as follows:

#include <stdlib.h>#include <stdio.h>#include <time.h> main( ){int i;srand( (unsigned)time( NULL ) );         for( i = 0; i < 10;i++ )            printf( "%d\n", rand()%100+1);}

 

Come from http://hi.baidu.com/akaneyu

2. Three general random number generators are recommended.
Function Name: Rand
Function: random number generator
Usage: void rand (void );
Program example:

#include <stdlib.h> #include <stdio.h> int main(void) {    int i;    printf("Ten random numbers from 0 to 99\n\n");    for(i=0; i<10; i++)       printf("%d\n", rand() % 100);    return 0; } 

Function Name: Random
Function: random number generator
Usage: int random (INT num );
Program example:

#include <stdlib.h> #include <stdio.h> #include <time.h> /* prints a random number in the range 0 to 99 */ int main(void) {    randomize();    printf("Random number in the 0-99 range: %d\n", random (100));    return 0; } 


Function Name: randomize!
Function: Initialize the random number generator.
Usage: void randomize (void );
Program example:

#include <stdlib.h> #include <stdio.h> #include <time.h> int main(void) {    int i;    randomize();    printf("Ten random numbers from 0 to 99\n\n");    for(i=0; i<10; i++)        printf("%d\n", rand() % 100);    return 0; } 


The random number generation algorithm is introduced in commonly used computer algorithms.

3. How to generate a random number within the specified range

Since the random number generated by rand ranges from 0 to rand_max, while rand_max is a large number, how can we generate a random number from X ~ What about the number of Y?

From X to Y, there is a number of Y-X + 1, so to generate the number from X to Y, you only need to write like this:

K = rand () % (Y-X + 1) + X;

In this way, you can generate random numbers in any range you want.

4. generate random numbers that are not repeated
1)

# Include <stdlib. h> # include <stdio. h> # include <stdio. h> # include <time. h> swap (int * pm, int * pn)/* must be switched with a pointer */{int temp; temp = * pm; * pm = * pn; * pn = temp;} int main (void) {int I, a [513];/* int * pa, * pb; */srand (unsigned) time (NULL);/* define this to generate different random numbers */for (I = 1; I <= 512; I ++) {a [I] = I; printf ("% 4d", a [I]) ;}for (I = 512; I >=1; I --) {/* pa = & a [I]; pb = & a [rand () % I + 1]; */swap (& a [I], & a [rand () % I + 1]); /* if the first one is random from I, it will not contain 0 * // * no pointer is defined, so the conclusion is the same */} printf ("\ n "); for (I = 1; I <= 64; I ++) printf ("% 4d", a [I]); getch ();/* wintc output */}

 

2)

 #include <stdlib.h> #include <stdio.h> #include<stdio.h>int main(void){   int a[100]={0};  int i,m;    for(i=1;   i<=99;   ++i)     printf("%4d",a[i] );srand( (unsigned)time( NULL ) );for(i=1; i<=99; i++){        while(a[m=rand()%100+1]);        a = i;}       for(i=1;   i<=99;   ++i)     printf("%4d",a[i] );getch();}

 

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: info-contact@alibabacloud.com 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.