C/C++中的随机函数(1)

本文介绍如何使用C++标准库中的rand函数生成伪随机整数,并通过实例展示如何设置种子及生成指定范围内的随机数。文章还讨论了使用取模运算生成短区间内随机数的近似均匀分布问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

rand

function

<cstdlib>

int rand ( void );

Generate random number

Returns a pseudo-random integral number in the range 0 to RAND_MAX.

 

This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using srand.

 

        RAND_MAX is a constant defined in <cstdlib>. Its default value may vary between implementations but it is granted to be at least 32767.

        A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

 

( value % 100 ) is in the range 0 to 99

( value % 100 + 1 ) is in the range 1 to 100

( value % 30 + 1985 ) is in the range 1985 to 2014

 

Notice though that this modulo为模operation does not generate a truly uniformly distributed random number in the span跨度,跨距,范围 (since in most cases lower numbers are slightly 些微地,轻微地;纤细地more likely), but it is generally a good approximation 接近;近似值;近似法for short spans.

 

Parameters

(none)

 

Return Value

An integer value between 0 and RAND_MAX.

 

Example

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

/* rand example: guess the number */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
int iSecret, iGuess;

/* initialize random seed: */
srand ( time(NULL) );

/* generate secret number: */
iSecret = rand() % 10 + 1;

do {
    printf ("Guess the number (1 to 10): ");
    scanf ("%d",&iGuess);
    if (iSecret<iGuess) puts ("The secret number is lower");
    else if (iSecret>iGuess) puts ("The secret number is higher");
} while (iSecret!=iGuess);

puts ("Congratulations!");
return 0;
}

 

Output:

 


Guess the number (1 to 10): 5
      The secret number is higher
Guess the number (1 to 10): 8
      
The secret number is lower
Guess the number (1 to 10): 7
       Congratulations!

 

      In this example, the random seed is initialized to a value representing the second in which the program is executed (time is defined in the header <ctime>). This way to initialize the seed is generally a good enough option for most randoming needs.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值