rand_s

產生虛擬亂數。 此函式是更安全的函 rand 式版本,具有 CRT 中安全性功能中所述 的安全性增強功能。

語法

errno_t rand_s(unsigned int* randomValue);

參數

randomValue
要保存所產生值的整數指標。

傳回值

如果成功則為零,否則為錯誤碼。 如果輸入指標是 NULL 指標 _randomValue_ ,函式會叫用不正確參數處理常式,如參數驗證 中所述 。 如果允許繼續執行,函式會傳回 EINVAL,並將 errno 設為 EINVAL。 如果函式因任何其他原因而失敗, *_randomValue_ 則會設定為 0。

備註

rand_s 函式會將範圍介於 0 到 UINT_MAX 的虛擬隨機整數寫入輸入指標。 rand_s 函式使用作業系統來產生密碼編譯安全的亂數。 它不會使用函式所產生的 srand 種子,也不會影響 所使用的 rand 亂數序列。

_CRT_RAND_S 包含函式的標頭 rand_s 之前 stdlib.h ,必須先定義常數,如下列範例所示:

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

#define _CRT_RAND_S
#include <stdlib.h>

rand_s 取決於 RtlGenRandom API,此 API 僅適用于 Windows XP 和更新版本。

需求

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

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

範例

// crt_rand_s.c
// This program illustrates how to generate random
// integer or floating point numbers in a specified range.

// Remember to define _CRT_RAND_S before you include
// stdlib.h.
#define _CRT_RAND_S

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

int main( void )
{
    int             i;
    unsigned int    number;
    double          max = 100.0;
    errno_t         err;

    // Display 10 random integers in the range [ 1,10 ].
    for( i = 0; i < 10;i++ )
    {
        err = rand_s( &number );
        if (err != 0)
        {
            printf_s("The rand_s function failed!\n");
        }
        printf_s( "  %u\n", (unsigned int) ((double)number /
                       ((double) UINT_MAX + 1 ) * 10.0) + 1);
    }

    printf_s("\n");

    // Display 10 random doubles in [0, max).
    for (i = 0; i < 10;i++ )
    {
        err = rand_s( &number );
        if (err != 0)
        {
            printf_s("The rand_s function failed!\n");
        }
        printf_s( "  %g\n", (double) number /
                          ((double) UINT_MAX + 1) * max );
    }
}

範例輸出

10
4
5
2
8
2
5
6
1
1

32.6617
29.4471
11.5413
6.41924
20.711
60.2878
61.0094
20.1222
80.9192
65.0712

另請參閱

數學和浮點支援
rand
srand