34. Guess a random number – solution
The computer "thinks of" a random number by generating it with the function rand() from the header <stdlib.h>.The function rand() is used together with srand(); without srand() it would not be possible to get different numbers every time the application is started. A useful link to an article that explains this: www.geeksforgeeks.org/rand-and-srand-in-ccpp/ A number obtained in this way is in a larger range than the task needs, because in the task the number must be in the interval [a,b].
This is achieved with the operator that computes the remainder of dividing two numbers (%).
If r is the number obtained with the function rand(), and secret is the random number we want in the given interval, then it can be found like this:
secret = a + r % (b - a + 1);
The remainder r % (b - a + 1) is a number from 0 to b − a, so secret is a number from a to b.Before the loop, the maximum number of guesses "p" has to be defined as follows:
p = (int)floor(log(b - a + 1) / log(2)) + 1;
where the functions floor and log are defined in the header <math.h>. This is the number of guesses that is always enough if the player halves the interval every time (binary search): for 100 numbers that is 7 guesses. Inside the loop the number N is entered, and then we check whether it is equal to, smaller than or greater than the generated random number "secret", and act accordingly:- If it is equal, set the logical variable to the value 1 (true)
- If it is smaller, print the message: "The secret number is greater"
- If neither of the above holds, print the message: "The secret number is smaller"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h> // the time.h header is needed for time()
/*
Write a program in which the computer thinks of a random integer in the interval [a,b]
and asks the user to guess it, helping with a message that shows whether the entered number
is smaller or greater than the secret one
*/
int main(void)
{
int N, a, b, secret, p, k = 0; // N - the guess, secret - the correct number, p - max number of guesses, k - guesses so far
time_t t1; // declare a time variable
srand((unsigned) time(&t1)); // seed the random number generator
int guessed = 0;
printf("a=?, b=?\n");
scanf("%d%d", &a, &b);
int r = rand();
secret = a + r % (b - a + 1);
// printf("secret=%d\n", secret);
p = (int)floor(log(b - a + 1) / log(2)) + 1;
do {
printf("Guess the secret number\n");
scanf("%d", &N);
k++; // the number of guesses increases by 1
if (N == secret) {
guessed = 1; // the number was guessed
}
else if (N < secret) {
printf("The secret number is greater\n");
}
else {
printf("The secret number is smaller\n");
}
}
while (!guessed && k < p); // stop when the number is guessed or there are no guesses left
// Check
if (guessed) {
printf("You guessed the number!!\n");
}
else {
printf("Bad guessing!! The number was %d.\n", secret);
}
return 0;
}
| Previous |< Loops – basic examples |
Next Nested loops – examples>| |
