Skip to content

Instantly share code, notes, and snippets.

@Ge0
Last active November 12, 2017 18:29
Show Gist options
  • Save Ge0/c7c0233167020730048f54872d990950 to your computer and use it in GitHub Desktop.
Save Ge0/c7c0233167020730048f54872d990950 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MIN 1
#define MAX 100
/**
* @brief Pick up a random number between @p min and @p max.
*
* @param min the minimum value for the random number.
* @param max the maximum value for the random number.
* @return a random number between @p min and @p max
*/
unsigned int
random_number(unsigned int min, unsigned int max);
/**
* @brief clean stdin to remove extra characters into it.
*/
void clean_buffer(void);
int main(int argc, const char* argv[]) {
// Initialize the seed for random numbers
srand(time(NULL));
// Do we continue playing ?
char choice = 'n';
do {
// Generate a number to guess
unsigned int secret_number = random_number(MIN, MAX);
// Number of guesses
unsigned int guesses = 0;
// Current shot
unsigned int input_number = 0;
do {
printf("Take a guess: ");
scanf("%d", &input_number);
clean_buffer();
++guesses;
if(input_number > secret_number) {
printf("It is lower!\n");
} else if(input_number < secret_number) {
printf("It is greater!\n");
} else {
printf("Congratulations! You took %d "
"guesses to find out the secret "
"number.\n",
guesses);
}
} while(secret_number != input_number);
printf("Do you want to play again? (y/n) ");
scanf("%c", &choice);
clean_buffer();
} while(choice == 'y');
return EXIT_SUCCESS;
}
inline unsigned int
random_number(unsigned int min, unsigned int max) {
return (rand() % (max - min + 1)) + min;
}
inline void
clean_buffer(void) {
char c;
while((c = getchar()) != '\n' && c != EOF);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment