如何使用rand()%打印x个数字

时间:2018-11-12 17:16:31

标签: c++ c++11 c++14

我该如何使用rand()打印10个数字,然后按最大排序?

#include <iostream>
using namespace std;

int main() {
    int b;
    cin >> b;
    srand(b);

    for (int i = 0; i < 10; i++){
       cout << rand() % 100000 << " ";
    }
}

1 个答案:

答案 0 :(得分:1)

您可以生成一个数组,进行打印,然后对其进行排序(然后重新打印?)。

注意:如果true randomness对您来说是一个问题,rand() + % is not suited

#include <array>
#include <algorithm>
#include <iostream>

int main()
{
    std::array<int, 10> data;
    std::generate(begin(data), end(data), rand);
    for (auto n : data) {
        std::cout << n << ", ";
    }
    std::cout << '\n';

    std::sort(begin(data), end(data));
    for (auto n : data) {
        std::cout << n << ", ";
    }
    std::cout << '\n';
}

演示:http://coliru.stacked-crooked.com/a/2e62855189995ab0

以下内容:how could I define an operator to be able to write std::cout << data whatever the type of data is?