srand()、rand()、time()函数的用法

本文介绍了如何使用srand()和rand()函数生成随机数。通过将srand设置为当前时间,确保每次程序运行时都能得到不同的随机数序列。示例代码展示了如何生成并显示10个随机数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

srand()就是给rand()提供种子seed。

如果srand每次输入的数值是一样的,那么每次运行产生的随机数也是一样的。

以一个固定的数值作为种子是一个缺点。通常的做法是 :以这样一句srand((unsigned) time(NULL));来取代,这样将使得种子为一个不固定的数,这样产生的随机数就不会每次执行都一样了。详细用法如下:

 1 #include <iostream>
 2 #include <stdlib.h>
 3 #include <time.h>
 4 using namespace std;
 5 int main()
 6 {
 7     /*Seed the random-number generator with current time 
 8     so that the numbers will be different every time we run.*/
 9     srand((unsigned)time(NULL));
10     
11     /* Display 10 numbers */
12     for(int i=0;i<10;i++)
13     {
14         cout<<rand()<<endl;
15     }
16     return 0;
17 }

 

rand(void)用于产生一个伪随机unsigned int 整数。 
srand(seed)用于给rand()函数设定种子。

srand 和 rand 应该组合使用。一般来说,srand 用于对 rand 进行设置。 
比如:

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
    srand(time(0));
    /* Display 10 numbers */
    for(int i=0;i<10;i++)
    {
        cout<<rand()%100<<endl;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/woaiheniunai/p/6035396.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值