使用rand和srand函数的C ++程序
可以使用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
热门推荐
10 祝贺新婚祝福语古代简短
11 盛夏的温馨祝福语简短
12 老公生日祝福语简短好看
13 住学长学姐祝福语简短
14 七一祝福语明信片文案简短
15 恩师退休花束祝福语简短
16 老师新婚快乐祝福语简短
17 白羊生日祝福语 简短独特
18 生日寿宴祝福语简短精辟