C++ 程序使用 rand 和 srand 函数
可以使用 rand() 函数在 C++ 中生成随机数。srand() 函数设定 rand() 使用的随机数生成器种子。
下面给出了一个使用 rand() 和 srand() 的程序 −
范例
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
srand(1);
for(int i=0; i<5; i++)
cout << rand() % 100 <<" ";
return 0;
}输出
以上程序的输出如下 −
83 86 77 15 93
在以上程序中,由于使用 srand(1),因此每次运行程序时输出都相同。
若想在每次运行程序时更改随机数序列,则可以使用 srand(time(NULL))。下面给出演示此方法的程序 −
范例
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
srand(time(NULL));
for(int i=0; i<5; i++)
cout << rand() % 100 <<" ";
return 0;
}输出
以上程序的输出如下 −
63 98 17 49 46
在同一程序的另一次运行中,获得的输出如下 −
44 21 19 2 83
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP