[C ++] C ++ random function

xiaoxiao2021-03-06  56

C random function (VC Program):

#include

#include

#include

Using namespace std;

#define max 100

Int main (int Argc, char * argv [])

{

SRAND (NULL)); // srand () function generates a random seed starting at the current time

For (int i = 0; i <10; i )

Cout << rand ()% max << endl; // max is the maximum value, its random domain is 0 ~ MAX-1

Return 0;

}

Rand () usually uses this:

Rand () does not require parameters, it returns an arbitrary integer from 0 to max, the maximum random number is usually a fixed large integer.

In this way, if you want to generate 10 integers of 0 ~ 10, it can be expressed as:

INT n = rand ()% 11;

In this way, the value of n is a random number of 0 to 10, and if to generate 1 to 10, this is true:

INT n = 1 rand ()% 11;

In summary, it can be expressed as:

A RAND ()% N

The A is the start value, n is the range of integers.

For the decimal of 0 to 1, it is possible to obtain an integer of 0 to 10, and then remove 10 random decimals of random to very bit by 10, if it is necessary to obtain a randomized decimal of random to a percentile, First, 10 integers of 0 to 100, and then in addition to 100, other cases.

Usually the random number generated by Rand () is the same as the last time, this is intentionally designed, and it is for easy program debugging. To generate different random numbers, you can use the SRAND (SEED) function to randomize. With the difference in SEED, you can produce different random numbers.

As mentioned, you can also include the Time.h header file, then use SRAND (Time (0)) to use the current time to randomize the random number generator, so that different random numbers can be obtained every twice. Sequence (as long as the interval between runs more than 1 second).

Random function: << THE C Programming Language >> (Basic method of random number generation)

INT randx = 0;

int rand ()

{

Randx = ranx * 1103515245 12345;

Return Randx;

}

Void Srand (INT A)

{

RANDX = a;

}

转载请注明原文地址:https://www.9cbs.com/read-114521.html

New Post(0)