c++ rand

 

在 C++ 中,可以使用 <cstdlib> 头文件中的 rand() 函数生成随机数。这个函数会生成一个介于 0 和 RAND_MAX(通常是 32767)之间的伪随机整数。通常情况下,你可能还需要使用 srand() 函数来设置随机数生成器的种子。

下面是一个简单的示例,展示了如何在 C++ 中使用 rand() 函数生成随机数:

cpp
#include <iostream> #include <cstdlib> #include <ctime> int main() { // 设置随机数种子 std::srand(std::time(0)); // 生成随机数 int random_number = std::rand(); // 输出随机数 std::cout << "Random number: " << random_number << std::endl; return 0; }

请注意,std::rand() 生成的随机数通常不是真正的随机数,而是伪随机数,它们是通过某个算法基于种子生成的一系列数字。因此,在每次运行程序时,如果不重新设置种子,将会得到相同的随机数序列。为了避免这种情况,可以使用 srand() 函数来设置种子,通常使用当前时间作为种子值,以便每次运行程序时都会得到不同的随机数序列。

另外,要注意 rand() 函数的范围是 0 到 RAND_MAX,这个范围可以通过 #include <cstdlib> 中的 RAND_MAX 常量获取。如果需要在其他范围内生成随机数,可以使用取模操作来调整范围。例如,要生成 1 到 100 之间的随机数,可以使用 rand() % 100 + 1

需要特别注意的是,rand() 函数不是线程安全的,如果在多线程环境下使用,可能会导致意外的结果。在多线程环境下,推荐使用 <random> 头文件中的更现代的随机数生成器

 

=============

(1) rand()函数:
   原型: int rand(void)
   功能: 产生从 [0,RAND_MAX] 之间的随机数,RAND_MAX为系统定义的宏, 32位机器上大小为32767。
   头文件: stdlib.h或者iostream

 

(2)srand()函数:
   原型: void srand(unsigned seed)
   功能: 产生随机数的起始发生数据,和rand函数配合使用
   头文件: stdlib.h或者iostream   time.h

   比如以当前时间作为起始发生数据:srand( (unsigned)time(0) );

 

(3) randomize()函数:
   原型: void randomize(void)
   功能: 通过time函数来初始化随机数发生器,和srand( (unsigned)time(0) )语句功能相同

   头文件: stdlib.h   time.h

 

(4)random()函数

     原型:int random(int num)

     功能:random函数返回一个0~num-1之间的随机数. random(num)是在stdlib.h中的一个宏定义

     头文件:stdlib.h

 

(5)产生[minNum, maxNum]范围内的整数随机数

复制代码
1 //产生[minNum, maxNum]的随机数
2 default_random_engine generator(time(0));
3 int myrand(int minNum, int maxNum)
4 {
5     std::uniform_int_distribution<int> distribution(minNum, maxNum);
6     return distribution(generator);
7 }
复制代码

 

 

注意几点:

1 从vc6.0以后randomize()和random()都已经不能用了,完全由srand()和rand()代替。但是在tc和c++ builder中还是可以用的(亲自测试),此时randomize、srand 和 random、rand两组之间可以任意组合,效果均没差别

2 如果没有初始化随机数发生器,程序每次重新运行产生的随机数都相同

3 若循环产生随机数,srand(time(0))不要放在循环内部,因为time()的精度是秒,如果两次time()之间程序没有超过一秒,其返回值是一样的,srand(time(0))设置的随机种子也就一样,产生的随机数也就一样

用法:(rand和srand比较通用,以下用它们举例)
1 产生[0,1]的小数:  rand()*1.0/RAND_MAX

2 产生[0,x]的整数:  rand()%(x+1)

3 产生[x,y]的整数:  rand()%(Y-X+1)+X(由于rand()产生的随机数最大为32767,因此如果范围内包括比32767大的数,要用 rand()*(y-x)/RAND_MAX +X  )

复制代码
#include<stdlib.h>

#include<stdio.h>

#include<time.h>

int main()

{

  srand((unsigned)time(0)); //srand放在循环外面

  for(int i=1;i<=10;i++)

     printf("%d ",rand()1);

}
复制代码

 【版权声明】转载请注明出处 http://www.cnblogs.com/TenosDoIt/archive/2013/04/15/3022029.html

==========

 例子代码:

#include <iostream>
#include <string>
#include <cstring>
#include <memory>

#include <ctime>
#include <cstdlib>

using namespace std;


class Point{
private:
    double x,y;
public:
    Point(double x, double y){
        x = x;
        y = y;
    }
    int GetPoint(){
        cout << x << y << endl;
        return 0;
    }
    friend double Distance(Point &a,Point &b);
    friend class Tool;
};


double Distance(Point &a ,Point &b){
    return a.x + b.x + a.y + b.y;
}

class Tool{
public:
    void GetX(Point & a){cout << a.x << endl;}
};

class Test{
public:
    Test(string s){str = s; cout << "Test create\n";}
    ~Test(){cout << "Test delete: " << str << endl;}
    string& getstr(){return str;}
    void setStr(string s){str = s;}
    void print(){cout << str<< endl;}

private:
    string str;
};


class C;
class B;
class A {
public:
    shared_ptr<B> pb;
    weak_ptr<C> pc;
    ~A(){cout << "delete A "<< endl;}
};
class B{
public:
    shared_ptr<A> pa;
    weak_ptr<C> pc;
    ~B(){cout << "delete B " << endl;}
};
class C{
public:
    ~C(){cout << "delete C " << endl;}
};

void func(){
    shared_ptr<B> pb(new B());
    shared_ptr<A> pa(new A());
    shared_ptr<C> pc(new C());
    pb->pa = pa;
    pa->pb = pb;
    pb->pc = pc;
    pa->pc = pc;
    cout << pb.use_count() << endl;
    cout << pa.use_count() << endl;
    cout << pc.use_count() << endl;
}



int main(){
    Point a(1.0,2.0);
    Point b(2.0,3.0);
    Tool t;
    t.GetX(a);

    cout << "distance:" << Distance(a,b) << endl;
    shared_ptr<Test> ptest (new Test("123"));
    ptest->print();
    ptest->setStr("hello");
    ptest->print();
    ptest.get()->print();
    (*ptest).print();
    ptest.reset(new Test("123"));
    ptest->print();
    
    shared_ptr<Test> ptest2(new Test("456"));
    cout <<"ptest2:" << ptest2.use_count() << endl;;
    ptest = ptest2;
    cout << "before reset:" <<ptest2.use_count() << " ptest1: " << ptest.use_count() << endl;
    ptest.reset();
    cout << "ptest2 cout:" << ptest2.use_count() << endl;
    cout << "after reset" << endl;
    ptest2.reset();
    cout << "done" << endl;

    shared_ptr<Test> ptest3(new Test("hello"));
    ptest3->print();
    //ptest3.release();

    func();

    auto add = [](int a, int b){return a + b;};
    auto add1 = [](int a, int b) -> int {return a + b;};
    cout << "add:"<< add(3,2) << " add1:" << add1(5,6) << endl;

    int tmp_a = 123;
    auto f = [tmp_a]()mutable { cout << ++tmp_a << endl;; }; // 不会报错
    // auto f1 = [tmp_a]()  { cout << ++tmp_a << endl;; }; // 报错
    cout << tmp_a << endl; // 输出:123
    f(); // 输出:124

    srand(time(0));
    cout << "rand:" << rand() << endl;
    time_t now = time(0);
    cout << "nowtime:" << now << endl;
    cout << "rand:" << rand() << endl;
    tm * ltm = localtime(&now);
    cout << "localtime: " << ltm->tm_year + 1900 << " month:" << ltm->tm_mon + 1 << " day:" << ltm->tm_mday << endl;


    cout << "end world!" << endl;
    return 0 ;
}

 

 

 

参考:

 

posted @ 2024-05-28 13:52  redrobot  阅读(17)  评论(0编辑  收藏  举报