source code of /small-scripts/stackexchange/dice.c

Last modified
Lines 66

Parent directory Download CGIread sitemap Main page

Quick links: (none)

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #define N_DICE 3
  5. /* Conveniently return the sum. */
  6. int roll_dice(int *dice)
  7. {
  8.     int i, sum;
  9.     for (i = sum = 0; i < N_DICE; i++)
  10.     {
  11.         dice[i] = rand()%6 + 1;
  12.         sum += dice[i];
  13.     }
  14.     return sum;
  15. }
  16. void print_dice(int *dice, int sum)
  17. {
  18.     int i;
  19.     printf("\n\n");
  20.     for (i = 0; i < N_DICE; i++)
  21.         printf("Die %d: %d\n", i + 1, dice[i]);
  22.     printf("-------------------\nTotal: %d\n\n", sum);
  23. }
  24. int main()
  25. {
  26.     int runs, dice[N_DICE], sum, old_sum, correct, correct_guesses;
  27.     char guess;
  28.     
  29.     srand(time(NULL));
  30.     correct_guesses = 0;
  31.     sum = roll_dice(dice);
  32.     
  33.     printf("How many times do you want to play? ");
  34.     for (scanf("%d", &runs); runs; runs--)
  35.     {
  36.         print_dice(dice, sum);
  37.         old_sum = sum;
  38.         sum = roll_dice(dice);
  39.         
  40.         printf(
  41.             "Do you think the next total will be higher, "
  42.             "the same, or lower than the previous total? "
  43.             "(h, s, l)\n"
  44.         );
  45.         scanf(" %c", &guess);
  46.         switch (guess)
  47.         {
  48.             case 'h': correct = sum > old_sum; break;
  49.             case 's': correct = sum == old_sum; break;
  50.             case 'l': correct = sum < old_sum; break;
  51.             default: correct = 0; printf("Not h, s or l.\n");
  52.         }
  53.         if (correct)
  54.         {
  55.             printf("You guessed correctly!\n");
  56.             correct_guesses++;
  57.         }
  58.         else
  59.             printf("You guessed incorrectly!\n");
  60.     }
  61.     printf("You got a total of %d guesses correct!\n", correct_guesses);
  62. }