1. 程式人生 > 實用技巧 >生成隨機數程式碼

生成隨機數程式碼

御用標頭檔案:#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的隨機數