lundi 30 janvier 2023

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.




Aucun commentaire:

Enregistrer un commentaire