C++ 库有一个名为 rand() 的函数,每次调用该函数都将返回一个非负整数。要使用 rand() 函数,必须在程序中包含 cstdlib 头文件。以下是其用法示例:
randomNum = rand();
该算法需要一个起始值,称为种子,以生成数字。如果没有给出一个种子,那么它将在每次运行时产生相同的数字流。
//This program demonstrates using the C++ time function
//to provide a nseed,T for the random number generator.
#include <iostream>
#include <cstdlib> // Header file needed to use srand and rand
#include <ctime> // Header file needed to use time
using namespace std;
int main()
{
unsigned seed; // Random generator seed
// Use the time function to get a "seed” value for srand
seed = time(0);
srand(seed);
// Now generate and print three random numbers
cout << rand() << " " ;
cout << rand() << " " ;
cout << rand() << endl;
return 0;
}
限制随机数的范围
number = (rand()%(maxValue - minValue +1)) + minValue;