/* -------------------------------------------------------------------------- // Figure 7.31 Can you guess my number? // Figure 7.32 Guessing a number. // -------------------------------------------------------------------------- */ #include "tools.h" void one_game( int tries ); #define TOP 1000 /* Top of guessing range. */ void main( void ) { int do_it_again; /* repeat-or-stop switch */ const int tries = ( log( TOP ) / log (2 ) ); /* This is one too few. */ banner(); puts( "\n This is a guessing game.\n" " I will think of a number and you must guess it.\n" ); srand( (unsigned) time( NULL ) ); /* seed random number generator */ do { one_game( tries ); printf( " \n\n Enter '1' to continue or '0' to quit: " ); scanf( "%i", &do_it_again ); } while (do_it_again != 0); bye(); } /* -------------------------------------------------------------------- // Play the game once. */ void one_game( int tries ) { int k; /* Loop counter. */ int guess; /* User's input. */ const int num = 1 + rand() % TOP; /* The hidden value. */ printf( " My number is between 1 and %i;" " I will let you guess %i times.\n" " Please enter a guess at each prompt.\n", TOP, tries ); for (k = 1; k <= tries; ++k) { printf( "\n Try %i: ", k ); scanf( "%i", &guess ); if (guess == num) break; if (guess > num) printf( " No, that is too high.\n" ); else printf( " No, that is too low.\n" ); } if (guess == num) printf( " YES!! That is just right. You win! \n" ); else printf( " Too bad --- I win again!\n" ); }