一个简单的打字练习程序 rand用法

来源:互联网 发布:女士手表 知乎 编辑:程序博客网 时间:2024/04/28 08:40
// test_rand.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <stdlib.h>#include <stdio.h>#include <conio.h>  //这个包含getch#include <time.h>int _tmain(int argc, _TCHAR* argv[]){    printf("this is a type practice program!\n");    while(1)    {    srand((unsigned) time(NULL)); /*播种子*/     printf("%c",'a'+rand()%26); //这个可用putchar('a'+rand()%26);代替    putchar(getch());//将输入的字母打印出来!    putchar(' ');    }        return 0;}

要取得[a,b)之间的随机整数,使用(rand() % (b-a))+ a (结果值将含a不含b)。
在a为0的情况下,简写为rand() % b。

  系统在调用rand()之前都会自动调用srand(),如果用户在rand()之前曾调用过srand()给参数seed指定了一个值,那么 rand()就会将seed的值作为产生伪随机数的初始值;而如果用户在rand()前没有调用过srand(),那么系统默认将1作为伪随机数的初始 值。如果给了一个定值,那么每次rand()产生的随机数序列都是一样的~~

    所以为了避免上述情况的发生我们通常用srand((unsigned)time(0))或者srand((unsigned)time(NULL))来 产生种子。如果仍然觉得时间间隔太小,可以在(unsigned)time(0)或者(unsigned)time(NULL)后面乘上某个合适的整数。 例如,srand((unsigned)time(NULL)*10)

/////////////////////////////

注意,在使用srand种种子时,千万不要把srand放到循环体中,因为每次循环耗费的时间很少,利用时间种出来的种子也是一样的,所以每个循环rand到的随机数也是一样的!!!!!