2013-09-10 63 views
2

如果我用srand註釋掉該行,該程序將工作,但沒有種子,因此每次的值都是相同的。該任務要求我使用rand,srandtime使骰子函數完全隨機。srand(time(NULL))in C++

#include <iostream> 
#include <cstdlib> 
#include <cmath> 
#include <ctime> 

using namespace std; 

int rollDice(); 
// function declaration that simulates the rolling of dice 

int main() { 

    int roll1 = rollDice(); 

    int roll2 = rollDice(); 

    // define, initialize, and combine dice roll total 

    int total; 

    total = 0; 

    total = roll1 + roll2; 

    * this is where a bunch of stuff is output to the screen from the dice rolls, using total as well as some other stuff that is being calculated, i left it out for simplicity* 

} 

// function to simulate a random dice roll 

int rollDice() { 

    int r; 

    srand (time(NULL)); 

    r = (rand() % 6) + 1; 

    return r; 

} 
+7

'srand'的文件,必須在你的程序只調用一次。 – ouah

+0

[看這個。](http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) – chris

+0

你的問題到底是什麼? – Goz

回答

5

srand放在主中並調用一次。 您必須使用一次種子從隨機序列中獲取所有結果。

在這裏你每次擲骰子時重新開始序列。

srand()

+0

感謝!我在google上看到的答案都沒有提到srand必須在主程序中初始化! – user2766542

+5

@ user2766542:要理解的主要問題是僞隨機數生成是如何工作的。你種下隨機數發生器,並給你一個可重現的數字序列。所以你一次種子,通常在'main()'中,但不一定。如果你每次都種下它,你會得到糟糕的結果。 'time()'具有一秒的粒度。所以如果你在一秒鐘內要求多個隨機數,它們可能都具有相同的值! –