简体   繁体   中英

Need help for a C Program Dice game based on betting

so I have to write a complete program to ask user to input amount and store it in the variable name balance, then ask user for the bet amount. If the amount is less than or equals balance amount, then roll dice. If the sum roll is 7 or 11, the player wins three times the bet. Otherwise, the player loses the bet. Player should be able to bet as long as he/she has money in balance.

I don't really get what else to do from here (from the code posted below) so please help me fix it.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>

int balance;
int sum;

int Ask_User_for_Bet(int b);
int Dice_Roll(void);
int Win_or_Lose();

int main()
{
    while(balance>0){
        int Ask_User_for_Bet(int b);
        int rollDice();
        int Win_or_Lose();
    }

    return 0;
}


int Ask_User_for_Bet(int b)
{
    printf("Enter bet amount");
    scanf("%d", b);
}

int rollDice(void) {
    sum=((rand() % 12) + 1);
    return ((rand() % 12) + 1);
}

int Win_or_Lose(){
    if(sum==7 || sum==11)
            printf("You won! Play again?");
    else
        printf("You lost! Play again?");



}

Lots wrong here.

balance and sum are not initialised to zero

int Ask_User_for_Bet(int *b)
{
    printf("Enter bet amount");
    scanf("%d", b);
// Or don't pass b, declare locally, pass &b then return
    }

Where do you reduce the balance?

roll_dice does not return both dice. Also, rand() will give you the same sequence each time.

You don't show the outcome!

Code-wise there's a few things I'd change

Use braces even for single statements.

Get rid of global vars balance & sum

Here:

while(balance>0){
    int Ask_User_for_Bet(int b);
    int rollDice();
    int Win_or_Lose();
}

the loop body is actually empty, because you haven't placed any statements, but prototype declarations. This, for example:

    int Ask_User_for_Bet(int b);

just tells the compiler that there is a function Ask_User_for_Bet that takes an int and that returns an int . This is equivalent (and redundant with) the same declarations made further above.

You want to call the functons instead, so:

while(balance>0){
    Ask_User_for_Bet(balance);
    rollDice();
    Win_or_Lose();
}

The call doesn't include any type information and just passed the desired arguments.

(Note that you will set sum to something else than the return value in rollDice() – you roll the die twice, when you want to roll it only once. And rolling a twelve-sided die once isn't the ame as rolling two six-sided dice. You will also have to check whether the balance can hold the bet and you have to do to balance, so that the while condition will become false at some time.)

As posted by others before there are many mistakes in your code. Instead of pointing them, I wrote some example code you can use (i tested it, it works) for your problem. You can study it and see where you have been wrong. For example your scanf's are no written correctly, they need a & operator, the rand will give you the same sequence each time, it needs a seed at start. Here is how you should use it in your main before running rand:

 int seed = time(NULL);
 srand(seed);

below is the code

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


int Ask_User_for_Balance(void);
int Ask_User_for_Bet(int balance_copy);
int rollDice(void);


int main(void){

    int balance=5; //something more than 0 (not necessary as you input the value later)
    int bet=0;
    int sum=0;  //the roll dice result

    //seed for random function
    int seed = time(NULL);
    srand(seed);

// enter balance    
    balance= Ask_User_for_Balance();

// main game loop

    while(balance>0){       
        bet= Ask_User_for_Bet(balance);
        sum= rollDice();
        printf ("dice roll is: %d\n", sum);

        //win or lose implementation
        if (sum==7 || sum==11){
            balance= balance + (bet*3);
             printf("You won! Current balance: %d \n ",balance);
        }
        else{
            balance=balance - bet;
            printf("You lost! Current balance: %d \n ",balance);

        }
    } // close while

    printf("Game Over...\n");

    return 0;
}


int Ask_User_for_Balance(void){

    int balance_temp;
    printf("Enter Balance\n");
    scanf("%d", &balance_temp);

    return balance_temp;

}

int Ask_User_for_Bet(int balance_copy){
    int bet_temp=0;

    //do not let the player bet more than his balance
    do{
        printf("Enter bet amount\n");
        scanf("%d", &bet_temp);
        if(bet_temp>balance_copy){
            printf("Please bet less than your balance\n");
        }
    }while (bet_temp>balance_copy);

    return bet_temp;
}


int rollDice(void) {
    int sum_temp;
    sum_temp=((rand() % 12) + 1);
    return sum_temp;
}

You have a large number of both logic and syntax errors in your code. Always compile with compiler warnings enabled (by adding -Wall -Wextra to your gcc compile string, or by adding /W3 to your cl.exe (VS) compile string).

Read and fix all warnings. Never accept code until it compiles cleanly, without any warning.

Validate ALL user input by checking the return of scanf (or any input function for that matter). You can further validate that any input received falls within the range of expected values.

Order your code so that your functions logically work together, and make use of the function returns. Do not declare global variables when they can be passed as parameters.

Putting that altogether, you could tweak your code similar to the following:

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

int get_user_bet (void);
int dice_roll (void);
int win_or_lose (int roll, int bet);

int main (void)
{
    int balance = 0, previous = 0, bet = 0, roll = 0, ch = 0;
    char c = 0;

    printf ("enter opening balance: $");
    if (scanf ("%d", &balance) != 1) {
        fprintf (stderr, "error: invalid input - balance.\n");
        return 1;
    }

    if (balance <= 0) {
        fprintf (stderr, "error: balance 0 or negative.\n");
        return 1;
    }

    while (c != 'n' && c != 'N' && balance > 0) {
        previous = balance;     /* save starting balance as previous */
        bet = get_user_bet();   /* get user bet */

        balance -= bet;         /* subtract from balance (at risk) */
        roll = dice_roll();     /* roll the dice */
        balance += win_or_lose (roll, bet); /* update bal. with win */

        printf ("bal. before: %d  bal. after: %d\n", previous, balance);
        if (balance > previous)
            printf ("\nYou won! Play again? "); /* display win */
        else
            printf ("\nYou lost Play again? "); /* display loss */

        if (scanf (" %c", &c) != 1) {   /* get answer to play again */
            fprintf (stderr, "error: user canceled.\n");
            break;
        }
        /* note you should clear any remaining chars from stdin here */
        for (ch = getchar(); ch != '\n' && ch != EOF; ch = getchar()) {}
    }

    return 0;
}

int get_user_bet()
{
    int b = 0;

    printf ("Enter bet amount: ");
    if (scanf ("%d", &b) != 1)
        return 0;

    return b;
}

int dice_roll (void)
{
    return rand() % 12 + 1;
}

int win_or_lose (int roll, int bet)
{
    printf ("roll was: %d\n", roll);

    if (roll == 7 || roll == 11)
        return bet + 3 * bet;

    return 0;
}

Example Use/Output

$ >bin\diceroll.exe
enter opening balance: $30
Enter bet amount: 10
roll was: 6
bal. before: 30  bal. after: 20

You lost Play again? y
Enter bet amount: 10
roll was: 12
bal. before: 20  bal. after: 10

You lost Play again? y
Enter bet amount: 10
roll was: 11
bal. before: 10  bal. after: 40

You won! Play again? y
Enter bet amount: 10
roll was: 5
bal. before: 40  bal. after: 30

You lost Play again? n

Look things over and let me know if you have any additional questions I can help you with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM