如果您正在使用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
你不熟悉使用循環? –
推動X-Y方向:[考慮使用'std :: uniform_real_distribution'](http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution)。它需要一些設置(包括在鏈接中),但它確實是你想要的東西(改變示例代碼「std :: uniform_real_distribution <> dis(1,2);'到'std :: uniform_real_distribution <> dis(0,1);') – user4581301
@CaptainObvlious C++沒有本地函數。聲明是指全球功能,無論它在哪裏。 – melpomene