[C++ program] random number

background

This is a real usage scenario (2020.9.4).

Every half day in the freshman camp, 2 students write an opinion. Among them, 5 students had already signed up the day before and finished their reading. So we should write a program to sort the remaining students and select the lucky ones to complete this task.

random number

There are several kinds of random numbers. One is the random number determined by the time function. For the program example, see [C++ Program] Line 59-60 in the Tic-Tac-Toe game (Human VS Lv1 computer) .
In addition, you can use the random number function that comes with the direct computer to generate random numbers:

Sample program

#include <iostream>
#include <random>
using namespace std;

int main()
{
    
    
    vector<unsigned> vec, vint;
    unsigned alr = 0, iter = 0;
    default_random_engine random;
    for (int i = 0; i != 1000; i++)
    {
    
    
        unsigned ran = random() % 31 + 1;
        vec.push_back(ran);
    }
    cout << "Let's choose the lucky dogs." << endl;
    for (unsigned iter = 0; iter != 1000; iter++)
    {
    
    
        if (vec[iter] != 5 && vec[iter] != 11 && vec[iter] != 12 && vec[iter] != 22 && vec[iter] != 26)
        {
    
    
            unsigned id = 0;
            for (unsigned i = 0; i != iter; i++)
            {
    
    
                if (vec[i] == vec[iter])
                    id = 1;
            }
            if (id == 0)
            {
    
    
                vint.push_back(vec[iter]);
                ++alr;
            }
        }
        if (alr == 20) break;
    }
    for (unsigned j = 0; j != 20; j++)
    {
    
    
        if (j % 4 == 0) cout << "\nSept." << j / 4 + 4 << ": ";
        if (j % 4 == 2) cout << "| ";
        if (vint[j] < 10)cout << "0";
        cout << vint[j] << " ";
    }
    cout << endl;
    return 0;
}

Sample output

Output

analysis

The output of this program is the same every time, because this is actually a random number table .
It's useless here uniform_int_distribution<unsigned> u(max, min), because it seems to be %convenient to use directly .


ALL RIGHTS RESERVED © 2020 Teddy van Jerry
welcome to reprint, please indicate the source.


See also

Teddy van Jerry’s navigation page
[C++ Program] Tic-Tac-Toe Game (Human VS Human)
[C++ Program] Tic-Tac-Toe Game (Human VS Lv1 Computer)
[C++ Program] Tic-Tac-Toe Game (Human VS Lv2 Computer)
[C++ Program 】 Tic-Tac-Toe Game (Human VS Lv3 Computer)
[C++ Program] Tic-Tac-Toe Game (Human VS Lv3 Computer) (Statistics Edition)
[C++ Program] Gobang Game (Human VS Human)
[C++ Program] Moving Maze Game
[C++ Program] Snake game
[C++ program] Digital push plate game (15-puzzle)
[C++ program] 2048 game

Guess you like

Origin blog.csdn.net/weixin_50012998/article/details/108399493