C++ 程式,用於生成給定範圍內的隨機數字序列


首先讓我們討論 rand() 函式。rand() 函式是 C++ 中的一種預定義方法。它在 <stdlib.h> 標頭檔案中宣告。rand() 用於在一定範圍內生成隨機數。其中 min_n 是隨機數的最小範圍,max_n 是數字的最大範圍。因此,rand() 將返回介於 min_n 到 (max_n – 1)(包含界限值)之間的隨機數。此處,如果我們分別將下限和上限指定為 1 和 100,則 rand() 將返回 1 到 (100 – 1) 之間的數值。即 1 到 99 之間。

演算法

Begin
   Declare max_n to the integer datatype.
      Initialize max_n = 100.
   Declare min_n to the integer datatype.
      Initialize min_n = 1.
   Declare new_n to the integer datatype.
   Declare i of integer datatype.
   Print “The random number is:”.
   for (i = 0; i < 10; i++)
      new_n = ((rand() % (max_n + 1 - min_n)) + min_n)
   Print the value of new_n.
End.

示例

#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
   int max_n = 100;
   int min_n = 1;
   int new_n;
   int i;
   cout<<"The random number is: \n";
   for (= 0; i < 10; i++) {
      new_n = ((rand() % (max_n + 1 - min_n)) + min_n);
      //rand() returns random decimal number.
      cout<<new_n<<endl;
   }
   return 0;
}

輸出

The random number is:
42
68
35
1
70
25
79
59
63
65

更新時間:30-7-2019

460 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始吧
廣告