C语言产生随机数的方法

betball贝博app C语言 523 次浏览 没有评论

用这两个头文件

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

生成语句

srand(time(NULL));//初始化随机数种子,通过系统时间来产生
key=rand()%10+1;//1~10
key=rand()%900+100;//100~999
rand()返回的值范围为[0,RAND_MAX],所以,配合取模,加法,可以产生一定范围的整数随机数。
附上一段猜大小程序代码
[cce_cpp]
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
	int key,i;
	int guess=0,count=0;
	srand(time(NULL));
//	key=rand()%10+1;//1~10
	key=rand()%900+100;//100~999
//	for(i=0;i<10;i++)
//		printf("%d\n",rand());//输出范围为0~65536
	while(count++<10){
		scanf("%d",&guess);
		if(guess==key){
			printf("ok!\n");return 0;}
		else if(guess<key)
			printf("<\n");
		else if(guess>key)
			printf(">\n");
	}
	printf("sorry\n");
	return 0;
}
[/cce_cpp]

发表评论

邮箱地址不会被公开。

Go