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

Time:11-16

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);
        }
    }
}

CodePudding user response:

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

CodePudding user response:

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].
    }
}
  •  Tags:  
  • c
  • Related