|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/jul08/guess.c
/*
making a guessing game:
Here, the computer picks a random number and we try to guess it
in as few tries as possible
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h> //needed to seed the generator to the computer clock
#define MAX 100 //defining the maximum number the computer will guess
int main(){
int ans, guess;
int count = 0;
time_t t;
/* Intializes random number generator */
srand((unsigned) time(&t)); // time(&t)- gets the time of day
//srand((unsigned) time(&t)) -seeds the generator to the computer clock
ans = rand() % MAX;// guessing the number
printf("--I'm thinking of a number--\n");
for(;;){ //loop while the user hasn't yet guessed the number
printf("Enter a guess: ");
scanf("%d", &guess);
if(ans > guess)
printf("Too low, guess again\n");
else if(ans < guess)
printf("Too high, guess again\n");
else
break; //the user got the number right, so get out of the loop
count++;
}
printf("You guessed correctly! thanks for playing!\n");
printf("It took you %d tries\n", count);
return 0;
}
|