生成随机数代码

御用头文件:#include<time.h>

产生小数与负数

 1 #include<bits/stdc++.h>
 2 #include<ctime>
 3 using namespace std;
 4 int main()
 5 {
 6     srand(time(0));//读入系统时间,种子数值
 7     double a;//小数
 8     for (int i = 0; i < 100; i++)
 9     if (rand() % 10 > 0.4)
10     {
11         cout << (rand() % 10) *0.1 << endl;
12     }
13     else
14     {
15         a = (rand() % 10) * -0.1;//这里*-0.1是为了产生小数的负数
16         if (a == -0.0)
17         {
18             cout << 0 << endl;
19         }
20         else
21         {
22             cout << a << endl;
23         }
24     }
25     return 0;
26 }

产生整数类型

 1 srand(time(0));
 2     double a;
 3    // for (int i = 0; i <n; i++)
 4     if (rand() % 10 >0){
 5         cofut << (rand() / 100) << endl;
 6     }else{
 7         a = (rand() / 100);
 8         if (a==0){
 9             cout<<0<<endl;
10         }else{
11             cout<<a<<endl;
12         }
13     }

产生范围随机数

  • 1-10范围内
 1 a=rand()%10//这里可更改 
  • 指定的数字到另一个更大的指定数字
 1 a=rand()%41+10//产生10-40的随机数 
 
原文地址:https://www.cnblogs.com/rebirth-death2019/p/13778598.html