Write a program that draws a number at random between 0 and 100. The user must guess the number by making propositions. With each guess, the program tells the user if it is larger or smaller. Here is an example:
AI > I think of a number between 0 and 100, you have to find it. Human > 50 AI > Too big! Human > 25 AI > Too small! Human > 35 AI > Too small! Human > 42 AI > Bravo, you found in 4 shots!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int secret, guess, nbTries = 0;
// Draw a number between 0 and 100
srand(time(NULL));
secret = rand() % 101;
printf("AI > I think of a number between 0 and 100, you have to find it.\n");
// Ask until the number is found
do {
printf("Human > ");
scanf("%d", &guess);
nbTries++;
if (guess > secret)
printf("AI > Too big!\n");
else if (guess < secret)
printf("AI > Too small!\n");
} while (guess != secret);
printf("AI > Bravo, you found it in %d tries!\n", nbTries);
return 0;
}
Write a program that queries the multiplication tables. The program will ask the multiplication again as long as the user's answer is wrong. When the user enters the correct answer, the program displays the time between the multiplication display and the correct answer. The program is exited by entering a negative number. At the end of the program, the average time is displayed:
8 x 1 = 8 You found in 1.4 seconds 8 x 6 = 40 8 x 6 = 48 You found in 11.9 seconds 7 x 9 = 64 7 x 9 = 63 You found in 11.9 seconds 9 x 9 = 81 You found in 3.1 seconds 3 x 0 = -1 ==> Average response time: 7.1 seconds
// clock_gettime() is a POSIX function (Linux, macOS)
#define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Return the current time in seconds
double now(void);
int main(void) {
int a, b, answer, nbQuestions = 0;
double start, duration, total = 0;
srand(time(NULL));
while (1) {
// Draw a multiplication
a = rand() % 11;
b = rand() % 11;
start = now();
// Ask again as long as the answer is wrong
do {
printf("%d x %d = ", a, b);
scanf("%d", &answer);
} while (answer >= 0 && answer != a*b);
// A negative number exits the program
if (answer < 0) break;
// Display the response time
duration = now() - start;
printf("You found in %.1f seconds\n", duration);
total += duration;
nbQuestions++;
}
// Display the average time
if (nbQuestions > 0)
printf(" ==> Average response time: %.1f seconds\n", total / nbQuestions);
return 0;
}
// Return the current time in seconds (with a resolution better than one second)
// clock() cannot be used here: it measures the processor time,
// which does not increase while the program waits for the keyboard.
double now(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec + t.tv_nsec / 1e9;
}