You know if I use a rand function in a loop, it may generate the same number twice, how to ensure that it generates distinct numbers? What to add with it.
Here is my code:
void main()
{
int m;
srand(time(NULL));
for (int c=1; c<=5; c++) {
m=rand() % 10 + 1;
cout<<m<<endl;}
getch();
}
Only call srand(time(NULL)); once in entire program. That's what you are doing, so this is fine.
void main() is just plain wrong, though. C++ insists on int main()
Edit: Do you actually not want the exact same number twice, or do you just want to not repeat the random sequence? In a random sequence, you will get repeats (otherwise it's not random).
1) Create an array that has all the possible outcomes you want (Each number exists only once in the array), then use random_shuffle to shuffle it up, and take the first 5 numbers.
or
2) Keep track of all the numbers you've generated so far (something like a std::set would be a good container to use for this) and keep "rerolling" if you get a number you already got.
#1 is more suitable for small sets, #2 is more suitable for larger sets. Since you are only generating numbers between 1 and 10, I would go with approach #1.
Side notes:
- main should return an int. Always. void main() is incorrect.
- In programming, things are generally zero based, not 1 based. You should try to get used to that. for (int c=1; c<=5; c++) this loop will work just fine, but is a little strange. A more typical loop would be: for (int c=0; c<5; c++). It doesn't really matter in this case, but when you start actually using the counter as an index in your loop, starting at 1 will screw you up.