天天看點

生成随機數代碼

禦用頭檔案:#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的随機數