带有随机数的C ++只有0到1

时间:2017-04-24 18:18:53

标签: c++

{Num of rows:3                                                                           Num of col: 2
 01
 00                                                                                       10}

我是C ++的新手,我终于得到了用户输入多少行和列的提示,但它也需要显示:

storeId

2 个答案:

答案 0 :(得分:4)

如果您使用的是C ++ 11,则可以使用:

#include <iostream>
#include <random>

static std::random_device rd;  // Random device engine, usually based on /dev/random on UNIX-like systems
static std::mt19937_64 rng(rd()); // Initialize Mersennes' twister using rd to generate the seed

// Generate random doubles in the interval [initial, last)
double random_real(double initial, double last) {
    std::uniform_real_distribution<double> distribution(initial, last);
    return distribution(rng);  // Use rng as a generator
}

// Generate random int in the interval [initial, last]
int random_int(int initial, int last) {
    std::uniform_int_distribution<int> distribution(initial, last);
    return distribution(rng);  // Use rng as a generator
}

int main() {
    int rows, columns;
    std::cout << "Enter the number of rows: ";
    std::cin >> rows;
    std::cout << "Enter the number of columns: ";
    std::cin >> columns;
    // For print a binary matrix.
    std::cout << "Binary Matrix" << std::endl;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < columns; ++j) {
            std::cout << random_int(0, 1) << " ";
        }
        std::cout << std::endl;
    }

    // For print a matrix with doubles in interval [0, 1)
    std::cout << "Double Matrix" << std::endl;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < columns; ++j) {
            std::cout << random_real(0, 1) << " ";
        }
        std::cout << std::endl;
    }
}

执行示例:

❯❯❯ g++ ../test.cc -std=c++11 -o test && ./test
Enter the number of rows: 3
Enter the number of columns: 4
Binary Matrix
0 1 0 0
1 0 1 0
0 0 1 0
Double Matrix
0.33597 0.384928 0.062972 0.109735
0.689703 0.111154 0.0220375 0.260458
0.826409 0.601987 0.94459 0.442919

答案 1 :(得分:0)

标准库有一个名为“random”的标题。

#include <random>
#include <ctime>

int main()
{
    std::srand(std::time(nullptr));
    int x = std::rand() % 2;
    return 0;
}