randomNum = rand();
但是,该函数返回的数字其实是伪随机数。这意味着它们具有随机数的表现和属性,但实际上并不是随机的,它们实际上是用算法生成的。
//This program demonstrates what happens in C++ if you
// try to generate random numbers without setting a "seed".
#include <iostream>
#include <cstdlib>// Header file needed to use rand
using namespace std;
int main()
{
// Generate and printthree random numbers
cout << rand() << " ";
cout << rand() << " ";
cout << rand() << endl ;
return 0;
}
第1次运行输出结果:
41 18467 : 6334
第2次运行输出结果:
41 18467 6334
// This program demonstrates using random numbers when a
// "seed" is provided for the random number generator.
#include <iostream>
#include <cstdlib> // Header file needed to use srand and rand
using namespace std;
int main()
{
unsigned seed; // Random generator seed
// Get a nseed" value from the user
cout << "Enter a seed value: ";
cin >> seed;
// Set the random generator seed before calling rand()
srand(seed);
//Now generate and print three random numbers
cout << rand() << " ";
cout << rand() << " ";
cout << rand() << endl;
return 0;
}
第1次运行结果:
Enter a seed value: 19
100 15331 - 209
第2次运行结果:
Enter a seed value: 171
597 10689 28587
//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;
}
程序输出结果:
2961 21716 181
number = rand() % max + 1;
例如,要生成 1?6 的随机数来代表骰子的点数,则可以使用以下语句:dice = rand() % 6 + 1;
这里简单介绍一下其工作原理。求余数运算符(%)可以获得整除之后的余数。当使用通过 rand 函数返回的正整数除以6时,余数将是 0?5 的数字。因为目标是 1?6 的数字,所以只需要给余数加 1 即可。number = (rand()%(maxValue - minValue +1)) + minValue;
在上述公式中,minValue 是范围内的最小值,而 maxValue 则是范围内的最大值。例如,要获得 10?18 的随机数,可以使用以下代码给变量 number 赋值:
const int MIN_VALUE = 10;
const int MAX_VALUE = 18;
number = rand() % (MAX_VALUE - MIN_VALUE + 1) + MIN_VALUE;
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有