简体   繁体   中英

I'm trying to get a random element in an array, why wont my simple code work?

I'm trying to get this snippet of code to work in a much larger solution, the problem is that the random part of the code never gets -1, only ever 0, 1 or 2 and 2 isn't even in the array. Can't figure this one out but its probably something simple.

#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");

}

Thank you all in advance.

rand() % setSize will give a number up to, but not including, setSize , as you noticed. You need to use this as an array index to get a random member of the array.

dx = numbers[rand() % setSize];

The rand() % setSize function returns an integer value between 0 and setSize. since you assigned setSize to 3 the range will be 0,1,2.

dx = (rand() % 3)-1; // use this to get -1 or 0 or 1 in random.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM