SO..I'm reading through a beginners code book and one of the exercises they have us do is have the Compiler generate a random number, and using a loop, we have to input new guesses until the number is found.
Got that one OK, at the end of the chapter, they challenge us to create the opposite: set a number, and using a number gen have the Compiler generate numbers until it is found.
the problem I'm having is that it keeps outputting the same number (I had to add a "break;" to stop the infinite loops)
QUESTION - how do i get it to generate a new number when the "getNum()" function is called? (I'm uber n00b, so there might be another way, this way just made sense to me....)
BONUS second question - Why is it always saying the value is too low?
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int guess,target;
int getNum(){
srand(static_cast<unsignedint>(time(0))); // only need this once
//reseeding srand with time(0) only changes the result of rand() once per second
guess = rand() % 100 + 1; // declaration of guess here overrides global declaration
// so this doesn't put anything into global int guess
cout<<"My guess is: "<<guess<<"\n";
return 0;
}
int main()
{
cout<<"Target Number - ";
cin>>target;
getNum();
do
{
if(guess > target) // when it gets here, global guess is still zero.
{
cout<<"Too High...\n";
srand (time(NULL)); //don't need this in here
getNum();
break; //infinite loop because guess is never > target
}
elseif(guess < target)
{
cout<<"Too Low...\n";
srand (time(NULL)); // don't need this here
getNum();
break; //infinite loop because global guess is always 0, < target
}
else
{
cout<<"YOU GUESSED IT!!!";
}
} while(guess != target);
system("Pause");
}
@PCrumley48 - Line 13 is not a declaration. It is an assignment. It does in fact change the global.
@OP - Using time() as an argument to srand() is fine. The point is your call to srand() is in the wrong place. srand() should be called ONCE. Move the call to srand() to line 18. Calling srand() multiple times within the same second will reset the RNG to the same sequence of numbers causing the RNG to return the same number each time it is called.
A word of advice. If you're going to try and guess a number, you want to make your getNum a little smarter. You should keep track of the highest and lowest number guessed. You should then generate a random number between between high and low. As your code is now, if you report the guess is too high, you will still possibly generate random numbers higher than that guess, which is pointless.
My bad. I was looking at your line 13, thinking it was his.
Well, it was as much my bad, too. I wanted him to see how the situation was causing the zero to be seen in main(). . .and the guess always being too low. Oh, well, "we can't all. . ."