advanced random number generator help


hello ,i need help with this number generator.
i want the program to tell me when i am close to the number he picked.
i.e : if the program generated 40 as a random number , if i type 35 , or 45 ,
the program will tell me that i am close to the number he picked.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>
  #include <cstdlib>
  #include <ctime>

using namespace std;
int main ()
{
  int numpicked = 0;//stores the number the user guesses
  int guessnum;//stores the number of tries 
  int numgenerated;//the generated number

cout<<"welcome ! i have picked a number between 1 and 100";
srand ((int)time(NULL));
numgenerated = rand() % 100+1;

for (guessnum=0 ; numgenerated != numpicked ; guessnum++)
{
cout<<"what would you like to guess? \n";
cin>>numpicked;

if(numpicked < numgenerated)//checks if the number picked is low

  cout<<"too low \n";

else if (numpicked > numgenerated)//checks if the number picked is high

  cout<<"too high \n";

}
cout<<"you guessed it! it took you "<<guessnum<<" guesses \n";

return 0;
}
Last edited on
a while loop would be more fitting than a for loop, given the logic of the program. Increment guessnum every time you go through the loop, and set a condition to break out of the loop if the answer is found. Here is some psuedo code:

while (guess is not answer)

if guess < answer
say something
else
say something

increment guessnum
repeat

say something
it could be better but you didn 't answer my question.
xxgixxx wrote:
it could be better but you didn 't answer my question.

What was your question? I don't see one.
My question is that I want the program to tell me when I am close to the random number not just lower or greater
What problem were you having doing that? Was there something about the code that you didn't understand that was making it hard for you to figure out what to do?
Topic archived. No new replies allowed.