Hello would someone be so kind as to explain if it is necessary to add the + 1 to the nLow and if so why... many thanks in advance.

// Generate a random number between nLow and nHigh (inclusive)

unsigned int GetRandomNumber(int nLow, int nHigh)

{

return (rand() % (nHigh - nLow + 1)) + nLow;

}

// Generate a random number between nLow and nHigh (inclusive)

unsigned int GetRandomNumber(int nLow, int nHigh)

{

return (rand() % (nHigh - nLow + 1)) + nLow;

}

Last edited on

Lets assume you give for nLow number 5 and nHigh number 10.

Rand() % (nHigh-nLow) -> rand() % 5 -> returns numers 0-4

Rand() % (nHigh-nLow+1) -> rand() % 6 -> returns numbers 0-5 and that is what function must add to nLow to work correctly by returning number from low to high

Rand() % (nHigh-nLow) -> rand() % 5 -> returns numers 0-4

Rand() % (nHigh-nLow+1) -> rand() % 6 -> returns numbers 0-5 and that is what function must add to nLow to work correctly by returning number from low to high

Topic archived. No new replies allowed.