Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- int game(int *nb_games, int *nb_win){
- (*nb_games)++;
- // random number generated by
- // rand() which generate a random number in the range 0 to RAND_MAX
- // rand() % 128, will give the modulo of rand() per 128, number in the range 0 to 127
- // then add 1, number in the range 1 to 128.
- int number = (rand() % 128) +1, i=0, value, c=0;
- // allow no-limit number of tries by removing c<4
- while(c<4 && ++c){
- printf("Enter a value: ");
- scanf("%d", &value);
- if(value < number) printf("greater\n");
- else if(value > number) printf("lesser\n");
- else {
- printf("number found\n");
- (*nb_win)++;
- return c;
- }}
- return c;
- }
- int main(int argc, const char *argv[]){
- int wanna_play=0, *record, nb_games=0, nb_win=0, len=1, total_tries=0;
- char tmp[4];
- // seeding the random number generator by using unique value 'time'
- srand(time(NULL));
- record = (int*) malloc(sizeof(int));
- do {
- // add the result of game() in the record[] and the count of total_tries
- total_tries += record[len-1] = game(&nb_games, &nb_win);
- printf("game ending with %d tries\nyour ratio of wins is %f for an average number of tries of %f\ndo you want to play again ? yes/no\n", record[len-1], (float)(nb_win/nb_games), (float)(total_tries/nb_games));
- // take only 3 chars of the answer
- scanf("%3s", tmp);
- // flush the input buffer
- while(getchar() != '\n');
- if(strcmp("yes", tmp, 3)==0){
- wanna_play=1;
- // re-allocation of record[] by adding one row for storing the next game history
- record = (int*) realloc(record, sizeof(int)*++len);
- }
- else wanna_play=0;
- } while (wanna_play);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement