御用头文件:#include<time.h>
产生小数与负数
#include<bits/stdc++.h>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));//读入系统时间,种子数值
double a;//小数
for (int i = 0; i < 100; i++)
if (rand() % 10 > 0.4)
{
cout << (rand() % 10) *0.1 << endl;
}
else
{
a = (rand() % 10) * -0.1;//这里*-0.1是为了产生小数的负数
if (a == -0.0)
{
cout << 0 << endl;
}
else
{
cout << a << endl;
}
}
return 0;
}
产生整数类型
srand(time(0));
double a;
// for (int i = 0; i <n; i++)
if (rand() % 10 >0){
cofut << (rand() / 100) << endl;
}else{
a = (rand() / 100);
if (a==0){
cout<<0<<endl;
}else{
cout<<a<<endl;
}
}
产生范围随机数
1-10范围内
a=rand()%10//这里可更改
指定的数字到另一个更大的指定数字
a=rand()%41+10//产生10-40的随机数

该篇博客介绍了如何在C++中利用头文件<time.h>和<ctime>生成随机数,包括小数、负数及指定范围内的整数。示例代码展示了通过srand(time(0))设置种子,并使用rand()函数产生不同类型的随机数,如小数、负数以及1-10范围内的整数。此外,还展示了如何生成10-40之间的随机数。
3430

被折叠的 条评论
为什么被折叠?



