Monday, July 27, 2009

C++ problem?

i'm having trouble trying to get to program to work...


i have to generate random numbers between 0 - 10...


and then if the user doesn't enter the correct number then it hints the user to guess higher or lower.


also the program will not end until the user types the correct number.





this is what i have...





#include %26lt;iostream%26gt;


#include %26lt;cstdlib%26gt;


#include %26lt;time.h%26gt;


using namespace std;


int main()


{


time_t seconds;





time(%26amp;seconds);





srand((unsigned int) seconds);





cout %26lt;%26lt; "Enter a number (0-10): " %26lt;%26lt;endl;


cin %26gt;%26gt; guess;





if(guess%26lt;rand)


{


cout%26lt;%26lt;"Guess higher: "%26lt;%26lt;endl;


cin %26gt;%26gt;guess;


}


if(guess%26gt;rand)


{


cout %26lt;%26lt;"Guess lower: "%26lt;%26lt;endl;


cin%26gt;%26gt;guess;


}


if(guess=rand)


{


cout%26lt;%26lt;"you are Correct!!"%26lt;%26lt;endl;


}





return 0;


}








what am i doing wrong??

C++ problem?
You aren't defining the variable that holds the random number. Something like this will generate a random number between 0 and 10:





int r = rand() % 11;





The whole guessing part should be inside a loop that continues until the guess equals the random number.
Reply:You are not enclosing your "ifs" for determining a correct answer on a loop. You need a "while" loop and if the guess is correct, you need to call "break".





As written, your code will only go through one pass.
Reply:Try this:





#include %26lt;iostream%26gt;


#include %26lt;cstdlib%26gt;


#include %26lt;time.h%26gt;


using namespace std;


int main()


{


time_t seconds;





time(%26amp;seconds);





srand((unsigned int) seconds);





int guess;


cout %26lt;%26lt; "Enter a number (0-10): " %26lt;%26lt;endl;


cin %26gt;%26gt; guess;





int nRand = rand() % 11; // not the best way of restricting the range, as the distribution will now be skewed, but good enough for a simple program like this





while (guess != nRand)


{


if(guess%26lt;rand)


{


cout%26lt;%26lt;"Guess higher: "%26lt;%26lt;endl;


cin %26gt;%26gt;guess;


}


if(guess%26gt;rand)


{


cout %26lt;%26lt;"Guess lower: "%26lt;%26lt;endl;


cin%26gt;%26gt;guess;


}


}





cout%26lt;%26lt;"you are Correct!!"%26lt;%26lt;endl;


}





return 0;


}


No comments:

Post a Comment