【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();
}
           
自动取名

 

posted @ 2020-07-20 15:39  ant_colonies  阅读(141)  评论(0编辑  收藏  举报