I would like to know how to get different random numbers within a range from 1 to 6, to include both numbers 1 and 6.
I have used this code:
n = rand() % 6 + 1;
but I end up with the same number .
How do I get to give me different numbers and not the same number consecutively ?
One of the more interesting areas of programming are the random numbers. These numbers aren't actually random, per se, but are more "pseudo-random" in that they were designed to be able to be replicated based on the 'seed' value that it initialized with. This means that if you have the same seed value, you can call rand() as many times as you want, and you will still be able to close your program, come back to it in a few days, and run it again with the exact same results. This means that with the same seed value (I believe yours is set to the default), you will get the same first number each time.
This is useful in scientific programs, but if you want a different random number each time, I would recommend (depending on the language - I'm going to write this to be C specific, but I'm pretty sure you could make this assumption for most programming languages and find similar functions) setting the seed value (in C/C++ this is done with srand() ) to the current time.
-
srand( time( NULL) );
-
//your call to rand here should now vary, make sure to run it a few times!
-
If you're not in C/C++ and you can't figure out how to change the seed value, post again and we'll do our best to track it down for you (though we'll probably start by asking what you Google searched ;).