C++ 程式使用 rand 和 srand 函式


可以使用 rand() 函式在 C++ 中生成隨機數。srand() 函式設定 rand() 使用的隨機數生成器種子。

下面給出了一個使用 rand() 和 srand() 的程式 −

範例

 線上演示

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;
int main() {
   srand(1);
   for(int i=0; i<5; i++)
   cout << rand() % 100 <<" ";
   return 0;
}

輸出

以上程式的輸出如下 −

83 86 77 15 93

在以上程式中,由於使用 srand(1),因此每次執行程式時輸出都相同。

若想在每次執行程式時更改隨機數序列,則可以使用 srand(time(NULL))。下面給出演示此方法的程式 −

範例

 線上演示

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;
int main() {
   srand(time(NULL));
   for(int i=0; i<5; i++)
   cout << rand() % 100 <<" ";
   return 0;
}

輸出

以上程式的輸出如下 −

63 98 17 49 46

在同一程式的另一次執行中,獲得的輸出如下 −

44 21 19 2 83

更新日期: 2020 年 6 月 25 日

481 次瀏覽

開啟您的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.