It is really quite simple. What you are trying to do is put an integer argument (0-10 = -10) into the
rand() method. It is not overloaded to do that. You obviously were trying 0
through 10, but the '-' operator subtracts.
An easy way to get a random number from 0 to 10 is to simply use the modulus operator:
int rnd = rand() % 10;
Any number % 10 will give you either 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9. If you want to set a range, you can use basic math:
int rand(int min, int max) {
return rand() % (max - min + 1) + min;
}
Say you want a random number from 5 to 7, you would call it like this:
rand(5, 7);This will mod a random number by 3 (7 - 5 + 1). Now you have a number that is either 0, 1, or 2. Add 5, and you have a number 5, 6, or 7.
As for displaying random number with a comma, you can just append a comma to then end of a random number. For instance, if I wanted to display 5 random numbers:
for (int i = 0; i < 5; i++) {
cout << rand(0, 10);
if (5 - i > 1) { // we don't want to add an extra comma at the end
cout << ", ";
}
}
Hope this helps!
Edited by destin, 04 February 2006 - 11:57 AM.