我實際上在學習C++語言,我在做Pig Game,它需要一個骰子來玩,我的問題是我的骰子總是滾動相同的數字,不管多少次我關閉CodeBlocks或重新運行程序。我想說的還有,我已經使用像一個變量:dice=rand() % 6 + 1
,但目前我使用:骰子模擬器Pig,C++
int roll() {
return rand() % 6 + 1 ;
}
,我認爲更好的(IDK爲什麼)。
任何解釋爲什麼這給了我一遍又一遍的相同的翻滾?非常感謝您的回答^^
我實際上在學習C++語言,我在做Pig Game,它需要一個骰子來玩,我的問題是我的骰子總是滾動相同的數字,不管多少次我關閉CodeBlocks或重新運行程序。我想說的還有,我已經使用像一個變量:dice=rand() % 6 + 1
,但目前我使用:骰子模擬器Pig,C++
int roll() {
return rand() % 6 + 1 ;
}
,我認爲更好的(IDK爲什麼)。
任何解釋爲什麼這給了我一遍又一遍的相同的翻滾?非常感謝您的回答^^
空調風格
std::srand(std::time(NULL)); // calling it once at the start of program is enough
//later in code
std::rand() % 6 + 1;
C++風格Source
std::default_random_engine generator; // there are many random engines in <random> header
std::uniform_int_distribution<int> distribution(1,6);
int dice_roll = distribution(generator); // generates number in the range 1..6
//For repeated uses, both can be bound together:
auto dice = std::bind (distribution, generator);
// calling dice() will generate number in the range 1..6 for example int number = dice();
至少在C中,在使用rand
之前,您應該致電srand(time(NULL));
。
只是爲了完整性:其實你不必調用srand()函數,如果你喜歡的行爲,也可能是一把調試。
現在正常工作!謝謝你! – BlackFolgore