1. 程式人生 > 實用技巧 >【0003】與隨機數有關的一些問題

【0003】與隨機數有關的一些問題

時間種子的隨機數的生成,需要#include <time.h>。

#include <time.h>

time_t ts;

unsigned int num = time(&ts);
srand(num);


// 或者

srand((unsigned int)(time(NULL)));
時間變化的隨機數種子

001、洗牌

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


void main()
{
    int a[54];
    for (int
i = 0; i < 54; i++) printf("%d ", a[i] = i); srand((unsigned int)time(NULL)); // 隨機數種子 for (int i = 0; i < 53; i++) { int num = i + rand() % (53 - i); // 洗牌核心 int temp = a[i]; a[i] = a[num]; a[num] = temp; } puts(
"\n"); for (int i = 0; i < 54; i++) printf("%d ", a[i]); getchar(); }
洗牌

002、生成密碼

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


void main()
{
    char str[10];
    for (int i = 0; i < 10; i++)
    {
        str[i] = 'A' + i;        
    }

    time_t times;
    srand((unsigned 
int)time(&times)); int length = rand() % 10 + 6; // 6-16位 for (int i = 0; i < length; i++) { int num = rand() % 10; printf("%c", str[num]); } getchar(); }
給使用者自動生成6-16位的密碼

003、隨機取名

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <locale.h>

/*
蒹葭蒼蒼,白露為霜。所謂伊人,在水一方。溯洄從之,道阻且長。溯游從之,宛在水中央。

蒹葭萋萋,白露未晞。所謂伊人,在水之湄。溯洄從之,道阻且躋。溯游從之,宛在水中坻。

蒹葭采采,白露未已。所謂伊人,在水之涘。溯洄從之,道阻且右。溯游從之,宛在水中沚。 
*/


void main()
{
    setlocale(LC_ALL, "zh-CN");
    wchar_t str[9] = {L'', L'', L'', L'', L'', L'', L'', L'', L'' };

    time_t times;
    srand((unsigned int)time(&times));
    int length = rand() % 2 + 1;

    putwchar(L'');
    for (int i = 0; i < length; i++)
    {
        int num = rand() % 9;
        putwchar(str[num]);
    }

    getchar();
}
           
自動取名