生成随机数代码

    科技2024-03-26  86

    御用头文件:#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的随机数
    Processed: 0.013, SQL: 8