问: C语言中产生随机数的函数是什么? C语言中产生随机数的函数是什么?(好象有两个)以及这两个函数的头文件是什么?
问题补充:
rand和srand有什么区别没?
答:
#include <stdio.h>
------------------------------------------------------------------------------------------------
#include <stdlib.h>
#include <stdio.h> #include <time.h> int i=0; float n; int n1; while(i<1) { n=rand(); if(n>0&&n<10.0) i++; } n1=(int) n;
------------------------------------------------------------------------------------------------
调用rand()函数需要的头文件是 <stdlib.h>
#include <stdlib.h> #include <stdio.h> #include <time.h> void main( void ) { int i; srand( (unsigned)time( NULL ) ); for( i = 0; i < 10;i++ )//产生10个随机数 printf( " %6d/n", rand() ); }
------------------------------------------------------------------------------------------------
算法2:线性同余法
1)将种子设为X0, 2)用一个算法X(n+1)=(a*X(n)+b) mod c产生X(n+1) 一般将c取得很大,可产生0到c-1之间的伪随机数 该算法的一个缺点是会出现循环。 给个C的程序 unsigned int seed = 0; //seed 为种子,要设为全局变量 void mysrand(int i) //初始化种子 { seed = i; } int myrand() //产生0--32767之间的随机数 { seed = (1000*seed+2008) % 32768; return seed; } 调用实例 #include <time.h> main() { int a; mysrand(time(0)); a = myrand(); return 0; }
------------------------------------------------------------------------------------------------
下面关于一个另问题的解答:
C语言库函数中的rand()的用法??
#include <stdlib.h>
#include <stdio.h> #include<conio.h> int main(void) { int i; printf("Ten random numbers from 0 to 99/n/n"); for(i=0; i<10; i++) printf("%d/n", rand()%100); getch(); return 0; } 为什么每次运行的结果都是一样的??关了重启结果还是一样!! 这结果哪像是随机啊?!! 求高手帮忙解释一下这个库函数的用法?如果能解释一下上面结果不随机问题最好.谢谢!
答:
函数rand所产生的随机数实际上是伪随机数,即反复调用函数rand所产生的一系列数似乎是随机的,但每次执行程序所产生的序列则是重复的。要产生真正的随机数序列,必须在每一次运行前为rand函数提供不同的种子,这是由srand函数提供的。
所以加上srand(time(NULL))就可以产生真正的随机数了。 #include <stdlib.h> #include <stdio.h> #include<conio.h> #include <time.h> int main(void) { int i; srand(time(NULL)); printf("Ten random numbers from 0 to 99/n/n"); for(i=0; i<10; i++) printf("%d/n", rand()%100); getch(); return 0; }
------------------------------------------------------------------------------------------------
在C51下的随机数生成
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |