2013-10-08 298 views
-1

我需要添加什麼,以便它不會連續選擇數字8而是數字1到9中的任何一個?函數srand?在C++中生成1到9之間的隨機數

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; 
} 
+0

看看'srand()'函數。 –

+0

如果你的編譯器支持C++ 11,那麼溝通'rand()'並使用新的隨機工具可能是明智的。這個問題很可能也是重複的。 – goji

+0

看起來你需要看你的括號()。試試'(rand()%8)+ 1'。 – 2013-10-08 03:52:14

回答

3

您需要首先初始化您的random seed

#include <stdlib.h>  /* srand, rand */ 
#include <time.h>  /* time */ 

srand (time(NULL)); 

僞隨機數生成器像rand()實際上並不是完全隨機的。相反,數字由發電機的初始狀態決定,稱爲種子。你的程序,就像它現在存在的那樣,在每次執行時都會有相同的種子 - 因此每次隨機數都是一樣的。

srand()來拯救 - 它讓你指定種子。

如果你要指定一個常量種子(如srand(2)),那麼你會遇到和現在一樣的問題,只是結果不同而已。因此,爲了保證每次程序執行時都有不同的結果,我們可以用當前時間初始化隨機數生成器 - 只要您從不及時旅行,就永遠不會得到完全相同的數字序列。

(注:在實際應用中,這可能不是很好,因爲有人可以重複利用(例如)手動重置系統時鐘不同的時間,這someone did once從賭場偷錢過去的結果。)

+0

是的,你需要srand。 – ChuckCottrill

+0

+1不是因爲世界上所有的麻煩而責備蘭特()。 –

相關問題