[英]Generate random number between 1 and 9 in c++
我需要添加什么,以便它不會連續選擇數字8,而是選擇1到9中的任何一個? rand
int main()
{
int iRand = (rand() % 9+1);
if (iRand==1)
{
cout << "The planet of the day is Mercury!" <<endl;
cout << "Mercury is the closest planet to the sun." <<endl;
}
else if (iRand==2)
{
cout << "The planet of the day is Venus!" <<endl;
cout << "Venus is the hottest planet in our solar system." <<endl;
}
// .... 3..4..5..6..7..8
else
{
cout << "The planet of the day is Pluto!" <<endl;
}
return 0;
}
您需要先初始化您的隨機種子 !
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
srand (time(NULL));
像rand()
這樣的偽隨機數生成器實際上並不是完全隨機的。 相反,數字由生成器的初始狀態(稱為種子)確定。 現在,您的程序在每次執行時都將具有相同的種子-因此,隨機數每次都將相同。
srand()
進行救援-它使您可以指定種子。
如果要指定一個常量種子(例如srand(2)
),那么您將遇到與現在相同的問題,只是結果不同。 因此,為了確保每次執行程序時都得到不同的結果,我們可以使用當前時間初始化隨機數生成器-因此,只要您從不按時間行進,就永遠不會獲得完全相同的數字序列。
(注意:在現實世界中的應用程序中,這可能不是很好,因為有人可以通過(例如)將系統時鍾手動重置為其他時間來重復過去的結果。 有人曾經一次從賭場偷錢。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.