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.
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace 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";
elseif (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;
}
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
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?