求0~1之间的随机数,还有就是srand的作用!

powereagle 2003-10-17 08:55:43
1,求0~1之间的随机数。
2,srand的作用!
...全文
52 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
jhyu 2003-10-17
  • 打赏
  • 举报
回复
1.
double randf()
{
return (double)(rand()/(double)RAND_MAX);
}
2.
各种编程语言返回的随机数(确切地说是伪随机数)实际上都是根据递推公式计算的一组数值,当序列足够长,这组数值近似满足均匀分布。如果计算伪随机序列的初始数值(称为种子)相同,则计算出来的伪随机序列就是完全相同的。这个特性被有的软件利用于加密和解密。加密时,可以用某个种子数生成一个伪随机序列并对数据进行处理;解密时,再利用种子数生成一个伪随机序列并对加密数据进行还原。这样,对于不知道种子数的人要想解密就需要多费些事了。当然,这种完全相同的序列对于一般人来说是非常糟糕的。要解决这个问题,需要在每次产生随机序列前,先指定不同的种子,这样计算出来的随机序列就不会完全相同了。
于是srand()的作用就体现出来了。可以在调用rand()函数之前调用srand( (unsigned)time( NULL ) ),这样以time函数值(即当前时间)作为种子数,因为两次调用rand函数的时间通常是不同的,这样就可以保证随机性了。你也可以使用srand函数来人为指定种子数。
daizh 2003-10-17
  • 打赏
  • 举报
回复
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void main( void )
{
int i;


srand( (unsigned)time( NULL ) );


for( i = 0; i < 30;i++ )
printf( "%d\n", rand()%2 );//求0~1之间的随机数。
}
ttlb 2003-10-17
  • 打赏
  • 举报
回复
1.static_cast<double>(rand()) / numiric_limits<int>::max();
2.设置时间种子,没有的话可能每次rand的值都一样。
kingofvc 2003-10-17
  • 打赏
  • 举报
回复
更正
1 rand()%10001/10000
kingofvc 2003-10-17
  • 打赏
  • 举报
回复
1.rand()%10000/10000
2.from MSDN
/* RAND.C: This program seeds the random-number generator
* with the time, then displays 10 random integers.
*/

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void main( void )
{
int i;

/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );

/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
printf( " %6d\n", rand() );
}


69,368

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧