Different Ways to create random number in C++

1) void srand(unsigned int seed):

    *It can create a pseudo random number, if the seed is the same, then the random number is the same.

    *The common way to use it is as follows:

                   srand((unsinged int)(time(NULL)))

     As the time differs, the random number differs.


2) int rand()

   *It will return a random number between 0 and RAND_MAX

   *If srand(unsigned int seed) is not called befored, then the seed is set to 1 by defaut.

   

    Example:

     a, for(int i=0;i<10;i++){  
          ran_num=rand() % 6;
          cout<<ran_num<<" ";
      }

     

      Output: 5 5 4 4 5 4 0 0 4 2 

      * Everytime the output remains the same.

   

   b, srand(1);
      for(int i=0;i<10;i++){  
          ran_num=rand() % 6;
          cout<<ran_num<<" ";
      }


      Output: 5 5 4 4 5 4 0 0 4 2 

      * Everytime the output remains the same, and the same as in exp a.


   c, srand(6);
      for(int i=0;i<10;i++){  
         ran_num=rand() % 6;
         cout<<ran_num<<" ";
      }

    

      Output: 4 1 5 1 4 3 4 4 2 2

          * Everytime the output remains the same.


   d, #include <ctime>
      srand((unsigned)time(0));
      for(int i=0;i<10;i++){  
         ran_num=rand() % 6;
         cout<<ran_num<<" ";
      }


      Output1: 3 2 1 0 3 5 3 2 2 1

      Output2: 0 1 5 2 1 0 2 4 4 2

          * Everytime the output is different.


      

 

3) To create a random int number in some fixed range:

[a,b):  (rand() % (b-a))+ a;

[a,b]:  (rand() % (b-a+1))+ a;

(a,b]:  (rand() % (b-a))+ a + 1;


Another way to get it is: a + (int)b * rand() / (RAND_MAX + 1)


4) To create a float number between 0 and 1: 

rand() / double(RAND_MAX)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值