简体   繁体   中英

How can I randomly generate integers in interval <-99,99> in c++?

I tried something like this but this generate only in interval (-99,0)

void input(int array [row][col]){
    for (int i = 0; i < row; i++){
        for (int j = 0; j < col; j++){
            array[i][j] = rand() % 99 + (-99);
        }
    }
}

You can use std::uniform_int_distribution for example something like

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(-99, 99);

If you want to use the "old-fashioned" rand() instead of std::uniform_int_distribution , you could also do this:

for (int i = 0; i < row; i++){
    for (int j = 0; j < col; j++){
        int rnd_val = rand() % 199 // This generates a random value 
                                   // in the interval [0, 198].

        array[i][j] = rnd_val - 99; // This shifts the interval to [-99,99].
    }
}

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