i looked at the tutorials of generating random numbers and it was too hard to understand:(.I just want one random number to be generated at the start of the program between 1 and 100 inclusive could anyone help?

Printable View

- 05-27-2006k1ll3rrandom number
i looked at the tutorials of generating random numbers and it was too hard to understand:(.I just want one random number to be generated at the start of the program between 1 and 100 inclusive could anyone help?

- 05-27-2006DesolationCode:
`srand(time(NULL));`

int num = (rand() % 99) + 1;

- 05-27-2006Richie T
Here's the main part of that code:

Code:`#include <ctime>`

int main (void)

{

srand (time(NULL));

int number;

//number = (rand() % (max - min + 1) + min);

//max = 100, min = 1

//just remember - rand () % some_int will return a value

//between 0 and (some_int - 1)

number = (rand() % (100 - 1 + 1) + min);

return 0;

}

Desolation's code was fine actually

[/edit] - 05-27-2006DesolationCode:
`class RandomNumber {`

public:

RandomNumber() : min(0), max(1) { }

// other constructors

inline operator int() {

return ((rand() % (max - min)) + min);

}

public:

int min, max;

};

Edit: Usage.Code:`RandomNumber randy;`

int rand_num = randy;

- 05-28-2006whiteflags
why should min and max both be zero if we use a constructor with no arguments? I'm sorry it just makes no sense. If you do that than rand() gets devided by zero?! Never even risk deviding by zero!

- 05-28-2006Desolation
I assumed that is was obvious you would set both min and max... You can set max to 1 to get rid of the problem.

- 05-28-2006jafet
You're abusing OOP :p here's a function which should do the same thing:

Guaranteed idiotproof! ;)

Code:`int randnum(long min = 0, long max = RAND_MAX)`

{

min %= RAND_MAX + 1;

max %= RAND_MAX + 1;

if(min == max)

{

return min;

}

if(min > max)

{

std::swap(min, max);

}

return rand() % ((max - min + 1)?(max - min + 1):RAND_MAX) + min;

}

Code:`randnum(1, 5); //1 ~ 5`

randnum(5, -5); //-5 ~ 0 ~ 5

randnum(-70, -4); //-70 ~ -4

randnum(6, 6); //6