I have to write a program that will run a random guessing game. The game is to be numbers from 1-100, the guesser gets 20 tries and at the end is supposed to be asked if they wo
The problem the compiler is warning you about is with these two lines:
int number;
//...
srand(number>0);
Here, you haven't given the variable number
an initial value, so it's uninitialised -- you have absolutely no way of knowing what the value might be at this point. In fact, it's likely to change every time you run your programme. Next you're asking whether the mystery value is greater than zero -- it might be, it might not, but you just don't know. It's mystery behaviour, which is what the compiler is warning you about.
Now of course, you're trying to initialise the random seed, so having this mystery behaviour might be what you're after! But unfortunately even that isn't going to work as it stands.
In C++, the expression number>0
is boolean, that is, the result of the expression is either true
or false
. But the srand()
function takes an unsigned int
as it's argument, so the compiler has to convert the bool
to an unsigned
, and it does so by changing false
to 0
, and true
to 1
(probably: I believe it's technically up to the implementation). So no matter what the initial value of number
, your random seed is only going to have one of two possible values -- not very random at all!
Better would be to use a random seed based on something (relatively) unpredictable. It's common for non-cryptographic needs to initialise a seed based on the current time. Something like:
#include
std::time_t now = std::time(0);
srand(static_cast(now));
would be fine.