如果我用srand
註釋掉該行,該程序將工作,但沒有種子,因此每次的值都是相同的。該任務要求我使用rand
,srand
和time
使骰子函數完全隨機。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;
}
'srand'的文件,必須在你的程序只調用一次。 – ouah
[看這個。](http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) – chris
你的問題到底是什麼? – Goz