c语言随机数

1

在说这个问题前先说说srand的作用和用法

srand()函数:

原型: void srand(unsigned seed)

功能: 产生随机数的起始发生数据,和rand函数配合使用

头文件: stdlib.h time.h

例:

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

int main(void)
 {
   int i;
   time_t t;
   srand((unsigned) time(&t));
   printf("Ten random numbers from 0 to 99

");
   for (i=0; i<10; i++)
   printf("%d
", rand()%100);
   return 0;
}

这时运行程序,会发现每次产生的随机数都不一样。这是因为这里采用了时间作为种子,而时间在每时每刻都不相同,所以就产生了"随机"的随机数了。所以,要想产生不同的随机数,在使用rand之前需要先调用srand。

2

如果代码改成

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
 {
     int i;
   //time_t t;
   printf("Ten random numbers from 0 to 99

");
   for (i=0; i<10; i++)
   {
       srand((unsigned) time(NULL));
       printf("%d
", rand()%100);
   }
   return 0;
 }

那么输出来的数字是一样的,说明rand要放在循环里面,srand要放在循环外面

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
       int i;
   srand((unsigned) time(NULL));
   printf("Ten random numbers from 0 to 99

");
   for (i=0; i<10; i++)
   printf("%d
", rand()%100);
   return 0;
}

这样输出来10个随机数

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
    int main(void)
 {
   int i;
   srand((unsigned) time(NULL));
   printf("3 random numbers from 0 to 99

");

   printf("%d
", rand()%100);
   printf("%d
", rand()%100);
   printf("%d
", rand()%100);
   return 0;
}

这样子也是输出3个随机数的 说明在rand前不要重复使用srand((unsigned) time(NULL)) 一个即可

3带有小数点的随机数和绝对处理

rand()函数返回值是-90到32767之间的数。。。

伪代码:

如果一位小数(float)(rand()%10 + 10 )/10.0f;

如果两位小数(float)(rand()%100 + 100 )/100.0f;

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

int main(void)
 {
   int i;

   srand(time(NULL));

   for (i=0; i<10; i++)
   {
     printf("%f
", (abs(rand())%10000+10000)/10000.0-1.00);

   }
   return 0;
}

作者:小德cyj
出处:http://www.cnblogs.com/dongzhuangdian
欢迎转载,希望注明出处

原文地址:https://www.cnblogs.com/dongzhuangdian/p/5059858.html