ccoin-flipping

C Coin Flip "You win/You lose" Message


I'm starting with coding and just tried making a simple coin flip function. I tried to make it to show a "you win" or "you lose" message if you chose the right one, but it didn't work. What can I do?

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

typedef enum coin {HEADS, TAILS} coin;

coin flipCoin();

int main()
{
    char answer;
    
    printf("Choose HEADS or TAILS\n");
    scanf(" %c", &answer);
    
    if( (answer=='h') || (answer=='t') ) printf("Let's start:\n");
    else printf("Let's start anyway...\n");
    
    srand( time(NULL) );

    for (int i=0; i < 1; i++)
        if (flipCoin() == HEADS) printf("HEADS\n");
        else printf("TAILS\n");
    
    return 0;
}

coin flipCoin()
{
    if (rand() % 2 == 0 ) return HEADS;
    else return TAILS;
}

Edit: the code I used for "win/lose":

if((answer=='h') && (flipCoin()== HEADS)) printf("You win!\n");
else printf("you lose!\n");
if((answer=='t') && (flipCoin()== TAILS)) printf("You win!\n");
else printf("you lose!\n");

Solution

  • The code you have posted doesn't seem to show that you have tried to display "you win" or "you lose". I'm not 100% sure why you decided to use a loop. I would have tried something similar to this:

    coin result = flipCoin();
    if(result== HEADS && answer == 'h'){
        printf("HEADS, you win!\n");
    }else if(result == TAILS && answer == 't'){
        printf("TAILS, you win!\n");
    }else{
        printf("You Lost");
    }
    

    The next thing you can try to do is allow the player to keep playing and count their score.