randomNum = rand();
但是,該函數返回的數位其實是偽亂數。這意味著它們具有亂數的表現和屬性,但實際上並不是隨機的,它們實際上是用演算法生成的。//This program demonstrates what happens in C++ if you // try to generate random numbers without setting a "seed". #include <iostream> #include <cstdlib>// Header file needed to use rand using namespace std; int main() { // Generate and printthree random numbers cout << rand() << " "; cout << rand() << " "; cout << rand() << endl ; return 0; }
第1次執行輸出結果:
41 18467 : 6334
第2次執行輸出結果:
41 18467 6334
// This program demonstrates using random numbers when a // "seed" is provided for the random number generator. #include <iostream> #include <cstdlib> // Header file needed to use srand and rand using namespace std; int main() { unsigned seed; // Random generator seed // Get a nseed" value from the user cout << "Enter a seed value: "; cin >> seed; // Set the random generator seed before calling rand() srand(seed); //Now generate and print three random numbers cout << rand() << " "; cout << rand() << " "; cout << rand() << endl; return 0; }
第1次執行結果:
Enter a seed value: 19
100 15331 - 209
第2次執行結果:
Enter a seed value: 171
597 10689 28587
//This program demonstrates using the C++ time function //to provide a nseed,T for the random number generator. #include <iostream> #include <cstdlib> // Header file needed to use srand and rand #include <ctime> // Header file needed to use time using namespace std; int main() { unsigned seed; // Random generator seed // Use the time function to get a "seed” value for srand seed = time(0); srand(seed); // Now generate and print three random numbers cout << rand() << " " ; cout << rand() << " " ; cout << rand() << endl; return 0; }程式輸出結果:
2961 21716 181
number = rand() % max + 1;
例如,要生成 1?6 的亂數來代表骰子的點數,則可以使用以下語句:dice = rand() % 6 + 1;
這裡簡單介紹一下其工作原理。求餘數運算子(%)可以獲得整除之後的餘數。當使用通過 rand 函數返回的正整數除以6時,餘數將是 0?5 的數位。因為目標是 1?6 的數位,所以只需要給餘數加 1 即可。number = (rand()%(maxValue - minValue +1)) + minValue;
在上述公式中,minValue 是範圍內的最小值,而 maxValue 則是範圍內的最大值。例如,要獲得 10?18 的亂數,可以使用以下程式碼給變數 number 賦值:
const int MIN_VALUE = 10;
const int MAX_VALUE = 18;
number = rand() % (MAX_VALUE - MIN_VALUE + 1) + MIN_VALUE;