zoukankan      html  css  js  c++  java
  • C++的随机数

    C++产生随机数

    C++中没有自带的random函数,要实现随机数的生成就需要使用rand()和srand()。

    不过,由于rand()的内部实现是用线性同余法做的,所以生成的并不是真正的随机数,而是在一定范围内可看为随机的伪随机数。

    srand()

    srand()可用来设置rand()产生随机数时的随机数种子。通过设置不同的种子,我们可以获取不同的随机数序列。

    可以利用srand((int)(time(NULL))的方法,利用系统时钟,产生不同的随机数种子。不过要调用time(),需要加入头文件< ctime >。

    void test01()
    {
    vector<char> c;
    c.push_back('A');
    c.push_back('B');
    c.push_back('C');
    c.push_back('D');
    c.push_back('E');

    deque<int> d;
    srand((int)time(0)); // 产生随机种子 把0换成NULL也行
    for (vector<char>::iterator it=c.begin() ;it!= c.end(); it++ )
    {
    for (int i = 1; i < 11; i++)
    {
    d.push_back((rand() % 100 + 1));      //这样写就是1到100随机啦
    }
    sort(d.begin(), d.end());
    d.pop_front();
    d.pop_front();
    int sum = 0;
    for (deque<int>::iterator vit = d.begin(); vit!=d.end();vit++)
    {
    sum += (*vit);
    }
    float Agv = sum / d.size();
    cout << "选手:" << (*it) << "平均分为" << Agv << endl;
    }

    }

  • 相关阅读:
    [Leetcode] Distinct Subsequences
    [Leetcode] Restore IP Addresses
    [Leetcode] Substring with Concatenation of All Words
    [Leetcode] Palindrome Partitioning II
    [Leetcode] Palindrome Partitioning
    [Leetcode] Maximal Rectangle
    [Jobdu] 题目1493:公约数
    [Leetcode] Merge k Sorted Lists
    [Leetcode] Gray Code
    opencv2-新特性及Mat
  • 原文地址:https://www.cnblogs.com/qq376142178/p/12359534.html
Copyright © 2011-2022 走看看