Carlo Viloria
Carlo Viloria

Reputation: 53

Trying to use random number generator in a coin flip program in C

Hello i'm trying to create a program where it counts the number of heads and tails in a coin flip simulator based on the number of coin flips the user inputs. The issue with this is that when i'm trying to count the number of heads and tails then increment them, it gives me just a random number and not within the range of flips given.

This is a sample output of my error

Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 1804289393
Number of tails: 846930886

Instead I want it to count it like this:

Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 7
Number of tails: 3

Here's the program :

#include <stdio.h>
#include "getdouble.h"
#include <time.h>
#include <stdlib.h>

int main(void) {
  printf("Coin Flip Simulator\n");
  printf("How many times do you want to flip the coin? ");
  int numFlip = getdouble();
  if(numFlip == 0 || numFlip < 0) {
    printf("Error: Please enter an integer greater than or equal to 1.\n");
  }
  int i = 0;
  int numHead = rand();
  int numTails = rand();
  for (i = 0; i < numFlip; i++) {
    
    if(numFlip%2 == 0) {
      numHead++;
    }
    else {
      numTails++;
    }
  }
  printf("Number of heads: %d\n", numHead);
  printf("Number of tails: %d\n", numTails);
  
  return 0;
} 

Thanks for the suggestions, it's my first time trying to use the random number generator.

Upvotes: 0

Views: 632

Answers (1)

user9706
user9706

Reputation:

I suggest you use an unsigned integer type for numFlip. The main issue is that you need to initialize numHead (sic) and numTails. You want to use srand() to seed the random number generate otherwise the result is deterministic. As you only have two options just record number of heads and determine the tails after the fact:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    srand(time(0));
    printf("Coin Flip Simulator\n");
    printf("How many times do you want to flip the coin? ");
    unsigned numFlip;
    if(scanf("%u", &numFlip) != 1) {
        printf("numFlip failed\n");
        return 1;
    }
    unsigned numHeads = 0;
    for(unsigned i = 0; i < numFlip; i++)
        numHeads += (rand() % 2); // removed ! when @Fe2O3 wasn't looking :-)
    unsigned numTails = numFlip - numHeads;
    printf("Number of heads: %u\n", numHeads);
    printf("Number of tails: %u\n", numTails);
}

and example output:

Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 2
Number of tails: 8

Upvotes: 5

Related Questions