随机数的使用
随机数:rand()与之对应的头文件为#include<stdlib.h>
例:
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
cout << rand() << endl;//输出的值为随机的一个值,不过每次运行程序的答案都一样
}
如果想每次运行的随机数不一样,则需要用到srand(time(nullptr)),叫做随机种子,与之对应的头文件为#include<time.h>,具体运用方法如下:
#include<iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
int main()
{
srand(time(nullptr));//随机种子,只需要写一次,不能写在循环里
/*
cout << rand() << endl;//加上随机种子后的结果是随机的
cout << rand()%100 << endl;//求模可以控制随机数的范围0~100
*/
int n = rand()%100;
if(n < 10)
{
cout << "Miss" << endl;//表示只有10%的概率
}
int m = rand() % 31 + 20;//表示从非0开始的随机数 概率=[20,50]
cout << m << endl;
}
下面附上两道题目
题目一:
先随机产生N个三位自然数输出,然后再输出其中同时是3、5、7倍数的数。(设N为100)
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main()
{
srand(time(nullptr));
int N = 100;
for(int i = 0 ; i < N ; i++)
{
int n = rand() % 1000;//表示范围为[0,999]
if(n > 99)
{
cout << n << endl;
if(n % 105 == 0){//是3,5,7的倍数也代表是他们乘积的倍数
cout << n << "是3,5,7的倍数" << endl;
}
}
}
return 0;
}
题目二:
随机产生N个大写字母输出,然后统计其中共有多少个元音字符。(设N为200)
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main()
{
srand(time(nullptr));
int ch,N = 200,count = 0;
for(int i = 0 ; i < N ; i++)
{
ch = rand() % 26 + 65;//[65,90]
cout << (char)ch << endl;
if(ch == 'A'|| ch == 'E'|| ch == 'I'|| ch == 'O'|| ch == 'U')
{
count++;
}
}
cout << "共有" << count << "个元音字符" << endl;
return 0;
}