| title |
rand | Microsoft Docs |
| ms.custom |
|
| ms.date |
11/04/2016 |
| ms.reviewer |
|
| ms.suite |
|
| ms.technology |
|
| ms.tgt_pltfrm |
|
| ms.topic |
article |
| apiname |
|
| apilocation |
msvcrt.dll |
msvcr80.dll |
msvcr90.dll |
msvcr100.dll |
msvcr100_clr0400.dll |
msvcr110.dll |
msvcr110_clr0400.dll |
msvcr120.dll |
msvcr120_clr0400.dll |
ucrtbase.dll |
api-ms-win-crt-utility-l1-1-0.dll |
|
| apitype |
DLLExport |
| f1_keywords |
|
| dev_langs |
|
| helpviewer_keywords |
generating pseudorandom numbers |
random numbers, generating |
numbers, pseudorandom |
rand function |
pseudorandom numbers |
numbers, generating pseudorandom |
|
| ms.assetid |
75d9df25-7aaf-4a88-b940-2775559634e8 |
| caps.latest.revision |
20 |
| author |
corob-msft |
| ms.author |
corob |
| manager |
ghogen |
| translation.priority.ht |
cs-cz |
de-de |
es-es |
fr-fr |
it-it |
ja-jp |
ko-kr |
pl-pl |
pt-br |
ru-ru |
tr-tr |
zh-cn |
zh-tw |
|
Generates a pseudorandom number. A more secure version of this function is available, see rand_s.
rand returns a pseudorandom number, as described above. There is no error return.
Remarks
The rand function returns a pseudorandom integer in the range 0 to RAND_MAX (32767). Use the srand function to seed the pseudorandom-number generator before calling rand.
| Routine |
Required header |
rand |
<stdlib.h> |
For additional compatibility information, see Compatibility in the Introduction.
// crt_rand.c
// This program seeds the random-number generator
// with the time, then exercises the rand function.
//
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void SimpleRandDemo( int n )
{
// Print n random numbers.
int i;
for( i = 0; i < n; i++ )
printf( " %6d\n", rand() );
}
void RangedRandDemo( int range_min, int range_max, int n )
{
// Generate random numbers in the half-closed interval
// [range_min, range_max). In other words,
// range_min <= random number < range_max
int i;
for ( i = 0; i < n; i++ )
{
int u = (double)rand() / (RAND_MAX + 1) * (range_max - range_min)
+ range_min;
printf( " %6d\n", u);
}
}
int main( void )
{
// Seed the random-number generator with the current time so that
// the numbers will be different every time we run.
srand( (unsigned)time( NULL ) );
SimpleRandDemo( 10 );
printf("\n");
RangedRandDemo( -100, 100, 10 );
}
22036
18330
11651
27464
18093
3284
11785
14686
11447
11285
74
48
27
65
96
64
-5
-42
-55
66
Floating-Point Support
srand
rand_s