当前位置: C语言 -- 标准库 -- <stdlib.h> -- rand

rand函数


概要:
#include <stdlib.h>
int rand(void);

描述:

该函数计算[0,RAND_MAX]范围内的伪随机整数序列。

该函数不需要避免与其它伪随机序列生成函数的调用发生数据竞争。实现应像没有库函数调用rand函数一样。


参数:
void

无。


返回值:

函数返回一个[0,RAND_MAX]范围内的伪随机整数。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
/*函数rand范例*/

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

int main(void)
{
    int maximum;  //最大数字。
    int randomNumber;  //生成的随机数。
    int count = 0;  //统计竞猜次数。
    int guessNumber;  //竞猜者猜的数。

    /*生成随机数。*/
    puts("Input the upper limit of the random number.");
    scanf("%d", &maximum);
    srand(time(NULL));
    randomNumber = rand()%maximum+1;

    /*竞猜随机数。*/
    printf("Guess a number(1 to %d)\n", maximum);
    do
    {
        scanf("%d", &guessNumber);
        ++count;
        
        if(randomNumber<guessNumber)
            puts("The random number is lower than your guess.");
        else if(randomNumber>guessNumber)
            puts("The random number is higher than your guess.");
        else
            printf("Congratulations! ");
    }while(randomNumber!=guessNumber);

    printf("You tried %d time%s.\n", count, (count>1)?"s":"");

    return 0;
}


结果:

生成一个随机数,然后竞猜该随机数,并统计竞猜次数。


相关内容:
srand 初始化伪随机整数生成器的函数。
RAND_MAX 表示最大伪随机整数的宏。