Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.87 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. int game(int *nb_games, int *nb_win){
  6.     (*nb_games)++;
  7.     // random number generated by
  8.     // rand() which generate a random number in the range 0 to RAND_MAX
  9.     // rand() % 128, will give the modulo of rand() per 128, number in the range 0 to 127
  10.     // then add 1, number in the range 1 to 128.
  11.     int number = (rand() % 128) +1, i=0, value, c=0;
  12.     // allow no-limit number of tries by removing c<4
  13.     while(c<4 && ++c){
  14.         printf("Enter a value: ");
  15.         scanf("%d", &value);
  16.         if(value < number) printf("greater\n");
  17.         else if(value > number) printf("lesser\n");
  18.         else {
  19.             printf("number found\n");
  20.             (*nb_win)++;
  21.             return c;
  22.         }}  
  23.     return c;
  24. }
  25.  
  26. int main(int argc, const char *argv[]){
  27.  
  28.     int wanna_play=0, *record, nb_games=0, nb_win=0, len=1, total_tries=0;
  29.     char tmp[4];
  30.     // seeding the random number generator by using unique value 'time'
  31.     srand(time(NULL));
  32.     record = (int*) malloc(sizeof(int));
  33.     do {
  34.         // add the result of game() in the record[] and the count of total_tries
  35.         total_tries += record[len-1] = game(&nb_games, &nb_win);
  36.         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));
  37.         // take only 3 chars of the answer
  38.         scanf("%3s", tmp);
  39.         // flush the input buffer
  40.         while(getchar() != '\n');
  41.         if(strcmp("yes", tmp, 3)==0){
  42.             wanna_play=1;
  43.             // re-allocation of record[] by adding one row for storing the next game history
  44.             record = (int*) realloc(record, sizeof(int)*++len);
  45.         }  
  46.         else wanna_play=0;
  47.     } while (wanna_play);
  48.  
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement