Hey, I was messing around with variables for a bit and I found a really easy way to generate a perfect random number, WITHOUT using the rand functions (or ctime). it looks like this:
1 2 3
int a, b, randNum;
randNum = a + b;
randNum %= 6;
It gives a new random number each time you run it.
Does this mean that we don't have to go:
1 2 3 4 5
#include <cstdlib>
#include <ctime>
srand(time(0));
int randNum;
randNum = rand();
All my variables (a, b, and randNum) were all zero with that code. That must be how my compiler initializes variables, idk.
What I do know is how srand works. It uses the amount of seconds since January 1st, 1970. And I do believe it also uses the remainder % method to generate a seemingly random number.
I suggest sticking to that and not your method. I think whatever your a and b variables are equal to when they were initialized are whatever was leftover in that memory address.
Your code doesn't generate anything random. The modulus operator (%) returns the remainder of a division. Therefore, the random number can be predicted given the value of a, and b. Your code relies on the contents of the associated memory addresses of a, and b in order to determine the value of the random number.
I found a really easy way to generate a perfect random number, WITHOUT using the rand functions (or ctime). it looks like this:
That does not generate random numbers. It has undefined output.
As dem7w2 said... it's possible to get zero every time. This will happen if your compiler zero's memory auotmatically (which some might do for debug builds).
But really, what's more likely happening is you're just using left-over stack space for your "random" numbers. IE: the number you're getting back depends on the numbers previously held on the stack. Call that function twice in a row and you'll probably get the same data. But call a different function in between them and you might get something different. But it isn't random, it's directly determined by what is put on the stack.
Anyway... no. rand() is not redundant. Err.. well it wasn't. I think C++11 introduced MersenneTwister as an alternative prng, so that's another option... which I guess does make rand redundant.
Sorry, I guess its just my compiler/text editor. I'm using code::blocks and apparently when it sees that a variable is not initialized code::blocks gives it a completely random value.