骰子模拟器Pig,C++

问题描述:

我实际上在学习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(); 
+0

现在正常工作!谢谢你! – BlackFolgore

至少在C中,在使用rand之前,您应该致电srand(time(NULL));

只是为了完整性:其实你不必调用srand()函数,如果你喜欢的行为,也可能是一把调试。