[英]Why rand() keep giving the same value?
Every time the function gets called, it's always "number = 5".每次调用该函数时,总是“number = 5”。 The number always stays 5. I checked it already to make sure that srand is only ran once some I'm confused.
数字始终保持为 5。我已经检查过它以确保 srand 只运行一次,有些我很困惑。 This is a function inside of a class.
这是一个类内部的函数。
int playType::getComputerMove(){
int number;
if(gamesPlayed == 0){
srand(time(NULL));
}
number = rand() % 1 + 5;
return number;
}
Your issue is with the order of operations.您的问题与操作顺序有关。
rand() % 1
is resolved before the adding five. rand() % 1
在添加 5 之前被解析。 Since n % 1 = 0
, you will always get 5. Essentially, what is happening is this:由于
n % 1 = 0
,你总是会得到 5。本质上,发生的事情是这样的:
number = (rand() % 1) + 5;
In order to fix this, you will want to add parenthesis this way:为了解决这个问题,您需要以这种方式添加括号:
number = rand() % (1 + 5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.