[英]I'm trying to get a random element in an array, why wont my simple code work?
我试图让这段代码在更大的解决方案中工作,问题是代码的随机部分永远不会得到-1,只有0,1或2和2甚至不在数组中。 无法想出这个,但它可能很简单。
#include <iostream>
#include <time.h>
using namespace std;
int main() {
srand(time(NULL));
int dy(0), dx(0);
const int setSize = 3;
int numbers[setSize] = { -1, 0, 1 };
for (int i(0); i < 50; ++i) {
dy = 0; dx = 0;
while (dx == 0 && dy == 0) { // makes sure the zombie actually moves somewhere
dx = rand() % setSize;
dy = rand() % setSize;
}
cout << "\n" << dy << "\t" << dx;
}
system("pause");
}
谢谢大家。
正如您所注意到的, rand() % setSize
将给出一个最多但不包括setSize
。 您需要将其用作数组索引以获取数组的随机成员。
dx = numbers[rand() % setSize];
rand()%setSize函数返回0和setSize之间的整数值。 因为您将setSize指定为3,所以范围将为0,1,2。
dx = (rand() % 3)-1; // use this to get -1 or 0 or 1 in random.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.