rand

產生虛擬亂數。 此函式以程式設計方式更安全的版本可供使用;請參閱 rand_s 。 所產生的 rand 數位在密碼編譯上並不安全。 如需以密碼編譯方式更安全的亂數產生,請使用 rand_s 或 中的 C++ 標準程式庫中 <random> 所宣告的函式。

語法

int rand(void);

傳回值

rand 傳回虛擬亂數,如上所述。 沒有傳回錯誤。

備註

rand 函式會傳回虛擬隨機整數,範圍介於 0 到 RAND_MAX (32767)。 在呼叫 rand 之前,使用 函 srand 式來植入虛擬亂數字產生器。

rand 函式會產生已知的序列,不適用於做為密碼編譯函式。 如需以密碼編譯方式更安全的亂數產生,請使用 rand_s 或 中的 C++ 標準程式庫中 <random> 所宣告的函式。

根據預設,此函式的全域狀態會限定于應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。

需求

常式 必要的標頭
rand <stdlib.h>

如需相容性詳細資訊,請參閱相容性

範例

// crt_rand.c
// This program seeds the random-number generator
// with a fixed seed, then exercises the rand function
// to demonstrate generating random numbers, and
// random numbers in a specified range.

#include <stdlib.h> // rand(), srand()
#include <stdio.h> // printf()

void SimpleRandDemo(int n)
{
    // Print n random numbers.
    for (int i = 0; i < n; i++)
    {
        printf("  %6d\n", rand());
    }
}

void RangedRandDemo(int range_min, int range_max, int n)
{
    // Generate random numbers in the interval [range_min, range_max], inclusive.

    for (int i = 0; i < n; i++)
    {
        // Note: This method of generating random numbers in a range isn't suitable for
        // applications that require high quality random numbers.
        // rand() has a small output range [0,32767], making it unsuitable for
        // generating random numbers across a large range using the method below.
        // The approach below also may result in a non-uniform distribution.
        // More robust random number functionality is available in the C++ <random> header.
        // See https://learn.microsoft.com/cpp/standard-library/random
        int r = ((double)rand() / RAND_MAX) * (range_max - range_min) + range_min;
        printf("  %6d\n", r);
    }
}

int main(void)
{
    // Seed the random-number generator with a fixed seed so that
    // the numbers will be the same every time we run.
    srand(1792);

    printf("Simple random number demo ====\n\n");
    SimpleRandDemo(10);
    printf("\nRandom number in a range demo ====\n\n");
    RangedRandDemo(-100, 100, 100000);
}```

```Output
Simple random number demo ====

    5890
    1279
   19497
    1207
   11420
    3377
   15317
   29489
    9716
   23323

Random number in a range demo ====

     -82
     -46
      50
      77
     -47
      32
      76
     -13
     -58
      90

另請參閱

數學和浮點支援
srand
rand_s
C++ <random> 程式庫