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
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?
Or something along the lines of this.Code:srand(time(NULL));
int num = (rand() % 99) + 1;
Here's the main part of that code:
[edit]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]
My compiler complains about this code but whatever, it should work.Code: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;
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!
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.
You're abusing OOP :p here's a function which should do the same thing:
Guaranteed idiotproof! ;)
UsageCode: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